Search code examples
stringrustcomparison

String references comparison in Rust


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);
}

Solution

  • 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.