How to check if two variables point to the same object in memory?

前端 未结 1 372
野的像风
野的像风 2020-11-30 13:42

For example:

struct Foo<\'a> { bar: &\'a str }

fn main() {
    let foo_instance = Foo { bar: \"bar\" };
    let some_vector: Vec<&Foo> =         


        
相关标签:
1条回答
  • 2020-11-30 14:23

    There is the function ptr::eq:

    use std::ptr;
    
    struct Foo<'a> {
        bar: &'a str,
    }
    
    fn main() {
        let foo_instance = Foo { bar: "bar" };
        let some_vector: Vec<&Foo> = vec![&foo_instance];
    
        assert!(ptr::eq(some_vector[0], &foo_instance));
    }
    

    Before this was stabilized in Rust 1.17.0, you could perform a cast to *const T:

    assert!(some_vector[0] as *const Foo == &foo_instance as *const Foo);
    

    It will check if the references point to the same place in the memory.

    0 讨论(0)
提交回复
热议问题