Skip to content

Unclear lifetime mismatch error with anonymous lifetimes #125143

Open
@cyrgani

Description

@cyrgani

Code

struct X;

impl std::ops::Add<&X> for &X {
    type Output = X;

    fn add(self, _rhs: Self) -> Self::Output {
        X
    }
}

Current output

error[E0308]: method not compatible with trait
 --> src/main.rs:8:5
  |
8 |     fn add(self, _rhs: Self) -> Self::Output {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
  |
  = note: expected signature `fn(&X, &X) -> X`
             found signature `fn(&X, &X) -> X`
note: the anonymous lifetime as defined here...
 --> src/main.rs:5:20
  |
5 | impl std::ops::Add<&X> for &X {
  |                    ^
note: ...does not necessarily outlive the anonymous lifetime as defined here
 --> src/main.rs:5:20
  |
5 | impl std::ops::Add<&X> for &X {
  |                    ^

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

Desired output

In the first part:

  = note: expected signature `fn(&X, &X) -> X`
             found signature `fn(&X, &X) -> X`

The different lifetimes should be shown since no difference is visible right now.

In the second part, one arrow should point at the right &X.

Rationale and extra context

No response

Other cases

When annotating the impl with two different lifetimes, the error message becomes more explanatory:

impl<'a, 'b> std::ops::Add<&'a X> for &'b X {
    type Output = X;

    fn add(self, _rhs: Self) -> Self::Output {
        X
    }
}

produces

error[E0308]: method not compatible with trait
  --> src/main.rs:16:5
   |
16 |     fn add(self, _rhs: Self) -> Self::Output {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected signature `fn(&'b X, &'a X) -> X`
              found signature `fn(&'b X, &'b X) -> X`
note: the lifetime `'a` as defined here...
  --> src/main.rs:13:6
   |
13 | impl<'a, 'b> std::ops::Add<&'a X> for &'b X {
   |      ^^
note: ...does not necessarily outlive the lifetime `'b` as defined here
  --> src/main.rs:13:10
   |
13 | impl<'a, 'b> std::ops::Add<&'a X> for &'b X {
   |          ^^

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

Rust Version

rustc 1.78.0 (9b00956e5 2024-04-29)
binary: rustc
commit-hash: 9b00956e56009bab2aa15d7bff10916599e3d6d6
commit-date: 2024-04-29
host: x86_64-unknown-linux-gnu
release: 1.78.0
LLVM version: 18.1.2

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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