Skip to content

Type inference fails when using associated type in traits #138057

Open
@StealthyKamereon

Description

@StealthyKamereon

Hello
I have noticed type inference fails in a case that seem rather obvious to solve.
Here is a link to a minimal reproduction project: https://github.com/StealthyKamereon/repro_bug_try_into/tree/master

The failure occurred when matching on the function TryInto::try_into: the inference is able to resolve the type of the Ok variant but not the Err one.

I tried this code:

fn repro() -> A {
    let b = B;
    // let a: A = match b.try_into() { // Compiles just fine
    let a = match b.try_into() { // Doesn't compile
        Ok(a) => a,
        Err(e) => { // e is unknown
            println!("Error converting: {:?}", e.to_string()); // e.to_string fails
            return A;
        }
    };
    a
}

struct A;

struct B;

#[derive(Debug)]
struct ConversionError;

impl Display for ConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Error")
    }
}

impl TryFrom<B> for A {
    type Error = ConversionError;
    fn try_from(_value: B) -> Result<Self, Self::Error> {
        Ok(A)
    }
}

I expected to see this happen: The compiler should be able to know that e is ConversionError because a is bound to A by the function signature.

Instead, this happened: The compiler cannot resolve the type of e.

Meta

rustc --version --verbose:

rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-pc-windows-msvc
release: 1.85.0
LLVM version: 19.1.7
Backtrace

error[E0282]: type annotations needed
  --> src\main.rs:14:48
   |
14 |             println!("Error converting: {:?}", e.to_string());
   |                                                ^ cannot infer type

For more information about this error, try `rustc --explain E0282`.
error: could not compile `repro_bug_try_into` (bin "repro_bug_try_into") due to 1 previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-bugCategory: This is a bug.T-compilerRelevant to the compiler 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