Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can two reference variables be equal in Rust?

Tags:

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?

like image 235
Aviral Srivastava Avatar asked Feb 04 '21 09:02

Aviral Srivastava


People also ask

Can two objects have same reference?

No, it never returns true unless you feed it the same exact object reference. The reason for it is that Java objects are not "embedded" in one another: there is a reference to B inside A , but it refers to a completely different object.

Can more than one reference variable refer to the same object?

Multiple reference variables can refer to the same object. The new operator is used to access an objects methods. A variable that is declared as a primitive type stores the actual value of the associated data. A variable that is declared as an object type stores a pointer to the associated object.

How do references work in Rust?

In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.


1 Answers

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.

like image 104
Bromind Avatar answered Oct 21 '22 05:10

Bromind