Skip to content

Type inference chooses wrong trait impl based on generic parameter #133225

Open
@Wasabi375

Description

@Wasabi375

I tried this code:

fn foo<T1, T2, E>(a: T1) -> Result<T2, E>
where
    T1: TryInto<usize>,
    T2: TryFrom<T1, Error = E>,
{
    a.try_into()
}

fn bar<T1, T2, E>(a: T1) -> Result<T2, E>
where
    T1: TryInto<usize>,
    T2: TryFrom<T1, Error = E>,
{
    TryInto::<T2>::try_into(a)
}

I expected to see this happen:

Both functions should compile.

Instead, this happened:

Only bar compiles.
foo produces the following compiler error:

error[E0308]: mismatched types
 --> src/main.rs:9:5
  |
4 | fn foo<T1, T2, E>(a: T1) -> Result<T2, E>
  |            --               ------------- expected `Result<T2, E>` because of return type
  |            |
  |            expected this type parameter
...
9 |     a.try_into()
  |     ^^^^^^^^^^^^ expected `Result<T2, E>`, found `Result<usize, ...>`
  |
  = note: expected enum `Result<T2, E>`
             found enum `Result<usize, <T1 as TryInto<usize>>::Error>`

For more information about this error, try `rustc --explain E0308`.

I also tried compiling with the new trait solver (rustc -Znext-solver src/main.rs) and get the same error message. I am not 100% sure if that means that I am compiling it the wrong way or if the output is just identical.

Meta

rustc --version --verbose:

rustc 1.84.0-nightly (5ec7d6eee 2024-11-17)
binary: rustc
commit-hash: 5ec7d6eee7e0f5236ec1559499070eaf836bc608
commit-date: 2024-11-17
host: x86_64-unknown-linux-gnu
release: 1.84.0-nightly
LLVM version: 19.1.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions