Skip to content

Improve error message when an operator is only implemented for references of a given type #66040

@gralpli

Description

@gralpli

If an operator (for example std::ops::Sub) is only implemented for references of a given type and you try to subtract two instances of that type directly, the error message doesn't give a clue that an implementation for references exists.

use std::ops::Sub;

struct Foo {}

impl Sub<&Foo> for &Foo {
    type Output = Foo;

    fn sub(self, other: &Foo) -> Self::Output {
        Foo {}
    }
}

fn main() {
    let a = Foo {};
    let b = Foo {};

    let c = a - b; // correctly fails, because `Sub` is only implemented for references
                   //  let c = &a - &b;  works
}
error[E0369]: binary operation `-` cannot be applied to type `Foo`
  --> src/main.rs:17:15
   |
17 |     let c = a - b;
   |             - ^ - Foo
   |             |
   |             Foo
   |
   = note: an implementation of `std::ops::Sub` might be missing for `Foo`

It would be nice if the error message said something like:

= note: an implementation of `std::ops::Sub` might be missing for `Foo`
= note: an implementation of `std::ops::Sub` exists for `&Foo`

… or even suggested to try &a - &b instead.


I came across this when trying to subtract two IndexSets (from the indexmap crate). I saw in the documentation that there was Sub implemented, but the compiler complained that subtracting was not possible. It took me a while to figure out that i had to add two &s.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`A-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.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions