7

I just confirmed how the Vec::contains works. I wrote code below and it looked working fine.

But I don't know why it works because it compares &String types. Does it mean String comparison works even they aren't dereferenced?

struct NewStruct {
    string_vec: Vec<Option<String>>,
}

fn main() {
    let mut mys = NewStruct {
        string_vec: Vec::<Option<String>>::new(),
    };
    mys.string_vec.push(Some("new array".to_string()));
    let ref_st = mys.string_vec.iter().filter(|o|o.is_some()).map(|o|o.as_ref().unwrap()).collect::<Vec<&String>>();
    println!("result:{:?}", ref_st.contains(&&("some string".to_string())));
    println!("result:{:?}", ref_st.contains(&&("new array".to_string())));
    println!("Hello, world!");
    f64::from(1234_u64 as i32);
}
fx-kirin
  • 1,906
  • 1
  • 20
  • 33
  • Does this answer your question? [What are Rust's exact auto-dereferencing rules?](https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules) – Jmb Feb 20 '20 at 08:13
  • 1
    @Jmb this is not because auto-dereferencing, but because equality on references compares the values. – mcarton Feb 20 '20 at 09:12

1 Answers1

19

Reference comparison on references in Rust always compares the values, never the addresses. This is true not just for &String but for any &T.

For example this does not compile because Foo does not implement PartialEq even though I'm only comparing references:

struct Foo;

fn main() {
    let a = Foo;
    let b = Foo;

    assert!(&a == &b);
}
error[E0369]: binary operation `==` cannot be applied to type `&Foo`
 --> src/main.rs:7:16
  |
7 |     assert!(&a == &b);
  |             -- ^^ -- &Foo
  |             |
  |             &Foo
  |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `&Foo`

The PartialEq implementation on references is

impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A where
    A: PartialEq<B> + ?Sized,
    B: ?Sized,

You can see that checking &A == &B requires to be able to do A == B.

mcarton
  • 27,633
  • 5
  • 85
  • 95