Skip to content

Confusing "cannot infer an appropriate lifetime" error message #65866

@DustinByfuglien

Description

@DustinByfuglien

Consider example:

trait Bar {
    fn bar(&self, r: &mut Re);
}

struct Re<'a> {
    data: &'a u16,
}

struct Foo;

impl Bar for Foo {
    fn bar<'a, 'b>(&'a self, r: &'b mut Re<'a>){}
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in generic type due to conflicting requirements
  --> src/lib.rs:12:5
   |
12 |     fn bar<'a, 'b>(&'a self, r: &'b mut Re<'a>){}
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 12:5...
  --> src/lib.rs:12:5
   |
12 |     fn bar<'a, 'b>(&'a self, r: &'b mut Re<'a>){}
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...but the lifetime must also be valid for the anonymous lifetime #3 defined on the method body at 12:5...
  --> src/lib.rs:12:5
   |
12 |     fn bar<'a, 'b>(&'a self, r: &'b mut Re<'a>){}
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: ...so that the method type is compatible with trait:
           expected fn(&Foo, &mut Re<'_>)
              found fn(&Foo, &mut Re<'_>)

error: aborting due to previous error

For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

All 3 notes of this error message is confusing:

note1, note2: Message not point where are the anonymous lifetime #1 and the anonymous lifetime #3. Also it's not obviously why there are two different anonymous lifetimes at one place (at 12:5).

=note3: Expected result looks totally equal to founded. So it's not obviously why it considered as different.

It is difficult to figure out what was going on.
May be some change of this message needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.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