Skip to content

Confusing error when implementing a trait over a reference and incorrectly using &self as parameter #118211

Open
@qsantos

Description

@qsantos

Code

struct S {}
trait Trait { fn f(self); }
impl Trait for &S {
    fn f(&self) { }
}

Current output

error[E0053]: method `f` has an incompatible type for trait
 --> src/lib.rs:4:10
  |
4 |     fn f(&self) { }
  |          ^^^^^
  |          |
  |          expected `S`, found `&S`
  |          help: change the self-receiver type to match the trait: `self`
  |
note: type in trait
 --> src/lib.rs:2:20
  |
2 | trait Trait { fn f(self); }
  |                    ^^^^
  = note: expected signature `fn(&S)`
             found signature `fn(&&S)`

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

Desired output

error[E0053]: method `f` has an incompatible type for trait
 --> src/lib.rs:4:10
  |
4 |     fn f(&self) { }
  |          ^^^^^
  |          |
  |          expected `&S`, found `&&S`
  |          help: change the self-receiver type to match the trait: `self`
  |
note: type in trait
 --> src/lib.rs:2:20
  |
2 | trait Trait { fn f(self); }
  |                    ^^^^
  = note: expected signature `fn(&S)`
             found signature `fn(&&S)`

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

Rationale and extra context

I found this specific part of the message confusing:

8 |     fn f(&self) {
  |          ^^^^^
  |          |
  |          expected `S`, found `&S`

I would expect it to say either:

8 |     fn f(&self) {
  |          ^^^^^
  |          |
  |          expected `&S`, found `&&S`

or:

8 |     fn f(&self) {
  |           ^^^^
  |           |
  |           expected `S`, found `&S`

Note that the error message is the exact same (but not the note) with this other example:

struct S {}
trait Trait { fn f(self); }
impl Trait for S {
    fn f(&self) { }
}

Of course, I might misinterpret how this message should be read. In any case, the attached note is perfectly clear, so this is a minor issue.

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemD-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.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