Skip to content

Suggest swapping LHS and RHS for PartialEq #130495

@bicarlsen

Description

@bicarlsen

Code

struct T(i32);

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

fn main() {
    println!("{:?}", 4i32 == T(4))
}

Current output

error[E0308]: mismatched types
  --> src/main.rs:10:30
   |
10 |     println!("{:?}", 4i32 == T(4))
   |                      ----    ^^^^ expected `i32`, found `T`
   |                      |
   |                      expected because this is `i32`

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

Desired output

error[E0308]: mismatched types
  --> src/main.rs:10:30
   |
10 |     println!("{:?}", 4i32 == T(4))
   |                      ----    ^^^^ expected `i32`, found `T`
   |                      |
   |                      expected because this is `i32`
help: `T` implements `PartialEq<i32>` consider swapping the LHS and RHS of the equality

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

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

Rationale and extra context

Because PartialEq<Rhs> is asymmetric, t == s and s == t are semantically different if s and t are different types. Because most people view == as being a symmetric operation, this could lead to confusion if T implements PartialEq<S> but S does not implement PartialEq<T>. Thus, providing a hint that swapping the LHS and RHS of the equality operator could elucidate why the error is occurring.

Other cases

No response

Rust Version

rustc 1.81.0 (eeb90cd 2024-09-04)
binary: rustc
commit-hash: eeb90cd
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.7

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