Skip to content

"expected X found X" diagnostic for lifetime mismatch in method signature of trait impl #79643

Closed
@SimonSapin

Description

@SimonSapin

With this code:

struct Foo(u32);

impl From<&Foo> for &u32 {
    fn from(foo: &Foo) -> &u32 {
        &foo.0
    }
}

The error message is:

error: `impl` item signature doesn't match `trait` item signature
   --> src/lib.rs:4:5
    |
4   |     fn from(foo: &Foo) -> &u32 {
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&Foo) -> &u32`
    |
    = note: expected `fn(&Foo) -> &u32`
               found `fn(&Foo) -> &u32`
    = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait`
    = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output

Now, the two help lines do give relevant information on how to fix this, which is to have a single named lifetime and use it everywhere:

struct Foo(u32);

impl<'a> From<&'a Foo> for &'a u32 {
    fn from(foo: &'a Foo) -> &'a u32 {
        &foo.0
    }
}

However the part of the error that is more visible at first glance (at least to me) is:

    = note: expected `fn(&Foo) -> &u32`
               found `fn(&Foo) -> &u32`

My internal reaction was: if what was expected and found is the same thing, what’s the problem?

The two signature are in fact not the same because they each have their own implicit lifetime parameter which don’t necessarily match each other. Would it make sense to make those parameters explicit? Signatures in diagnostics don’t need to be entirely valid Rust syntax. Something like:

    = note: expected `fn(&'_1 Foo) -> &'_1 u32`
               found `fn(&'_2 Foo) -> &'_2 u32`

Meta

The output is the same in 1.48.0 and nightly-2020-11-30.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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