Skip to content

Suggest swapping the equality when the message can't compare occurs #132695

Closed
@makai410

Description

@makai410

Code

// inspired by https://github.com/rust-lang/rust/issues/130495
struct T(String);

impl PartialEq<String> for T {
    fn eq(&self, other: &String) -> bool {
        &self.0 == other
    }
}

fn main() {
    String::from("123") == T(String::from("123"));
}

Current output

error[E0277]: can't compare `String` with `T`
  --> src/main.rs:11:25
   |
11 |     String::from("123") == T(String::from("123"));
   |                         ^^ no implementation for `String == T`
   |
   = help: the trait `PartialEq<T>` is not implemented for `String`
   = help: the following other types implement trait `PartialEq<Rhs>`:
             `String` implements `PartialEq<&str>`
             `String` implements `PartialEq<Cow<'_, str>>`
             `String` implements `PartialEq<str>`
             `String` implements `PartialEq`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

error[E0277]: can't compare `String` with `T`
  --> src/main.rs:11:25
   |
11 |     String::from("123") == T(String::from("123"));
   |                         ^^ no implementation for `String == T`
   |
   = help: the trait `PartialEq<T>` is not implemented for `String`
   = help: the following other types implement trait `PartialEq<Rhs>`:
             `String` implements `PartialEq<&str>`
             `String` implements `PartialEq<Cow<'_, str>>`
             `String` implements `PartialEq<str>`
             `String` implements `PartialEq`
   = note: `T` implements `PartialEq<String>`
help: consider swapping the equality
   |
11 |     T(String::from("123")) == String::from("123");
   |     ~~~~~~~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~~~


For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Rationale and extra context

In this case where T implements PartialEq<String>, swapping the equality is a good way to fix it.
Although #132404 has implemented this, it only covers the case where error[0308]: mismatched types occurs.

Other cases

No response

Rust Version

1.84.0-nightly (2024-10-15 e7c0d27) (playground)

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`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