rust-lang / rust-lang/rust

Trait solver fails to see trait is implemented for all values of const generic param

Open
#145,133 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-generics A-trait-system C-feature-request T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

trait RandomTrait
{
    type Item;
}

struct BoolWrapper<const VAL : bool>;

impl RandomTrait for BoolWrapper<true>  { type Item = String; }
impl RandomTrait for BoolWrapper<false> { type Item = i32;    }

// RandomTrait is now implemented for all possible values
// of the constant generic parameter of BoolWrapper. There
// exists no bool X for which BoolWrapper<X> does not
// implement RandomTrait.
//
// And yet...

trait BoolWrapperTypeConstructor
{
    type Of<const VAL : bool> : RandomTrait;
}

struct BoolWrapperFamily;

impl BoolWrapperTypeConstructor for BoolWrapperFamily {
    type Of<const VAL : bool> = BoolWrapper<VAL>;
}

I expected the code to compile, as RandomTrait is implemented for all 'flavors' of BoolWrapper.
Instead, the trait solver does not recognize that true and false are the only possible values a bool can have, and assumes that RandomTrait is not implemented for all possible types constructable by BoolWrapper.
This surprises me since a match expression can, in fact, recognize at compile-time whether all possible variants/values of a type are handled, in even more sophisticated ways than possible with const generics.

Meta

rustc --version --verbose:

rustc 1.86.0 (05f9846f8 2025-03-31)
binary: rustc
commit-hash: 05f9846f893b09a1be1fc8560e33fc3c815cfecb
commit-date: 2025-03-31
host: x86_64-pc-windows-msvc
release: 1.86.0
LLVM version: 19.1.7

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the provided BoolWrapper and BoolWrapperTypeConstructor reproducer with rustc 1.86.0 and inspect the trait solver's handling of const-generic bool exhaustiveness. The issue is resolved when the compiler recognizes that RandomTrait is implemented for every possible BoolWrapper value and accepts the associated type definition.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.