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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With