Aviral Srivastava
Aviral Srivastava

Reputation: 4582

How can two reference variables be equal in Rust?

I have a code that has a bug in one of the functions:

fn is_five(x: &i32) -> bool {
    x == 5
}

fn main() {
    assert!(is_five(&5));
    assert!(!is_five(&6));
    println!("Success!");
}

While running, the error is:

error[E0277]: can't compare `&i32` with `{integer}`
 --> main.rs:2:7
  |
2 |     x == 5
  |       ^^ no implementation for `&i32 == {integer}`
  |
  = help: the trait `std::cmp::PartialEq<{integer}>` is not implemented for `&i32`

error: aborting due to previous error

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

I fixed it by the logic of comparing two values and not one address and one value.

fn is_five(x: &i32) -> bool {
    *x == 5
}

However, I also tried (randomly) to use the borrowing method and to my surprise, it worked.

fn is_five(x: &i32) -> bool {
    x == &5
}

I do not understand how two addresses can be same? Is it that == operator has some trait that gets the value stored at both ends?

Upvotes: 8

Views: 2921

Answers (1)

Bromind
Bromind

Reputation: 1138

To be able to do ==, one must implement PartialEq. If you check the docs here, you can see that if a type A implements PartialEq<B> then &'_ A implements PartialEq<&'_ B>. In other words, if you can compare values, you can compare them using references.

The same reasoning applies for other comparison traits: Eq, PartialOrd, and Ord, and for mutable references.

Upvotes: 6

Related Questions