How Strings are compared in Rust? [duplicate]
fn main() {
let v1 = 5;
let v2 = 5;
let mut s = String::new();
s.push_str("a");
println!("{}", "a" == "a");
println!("{}", String::from("a") == String::from("a"));
println!("{}", String::from("a") == s);
println!("{}", &String::from("a") == &s);
println!("{}", &v1 == &v2);
}
Why does comparing different String instances, or even references to different String instances, (that though have the same value) results equal? Those are different pointers to even different locations (because the instances are different), aren't they?
Solution 1:
Maybe you read &v1 == &v2
as in C, but in Rust this is different.
Rust does not compare the references (addresses in C), but the values behind the references.
The previous expression is similar to *(&v1) == *(&v2)
; the comparison through references (impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A where A: PartialEq<B>
) is just a convenience.
For example, if r1
and r2
are references, then r1 == r2
is easier to read/write than *r1 == *r2
but it performs the same comparison.