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

For instance:

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

fn main() {
    let foo_instance = Foo { bar: "bar" };
    let some_vector: Vec<&Foo> = vec![&foo_instance];

    assert!(*some_vector[0] == foo_instance);
}
  • I want to check if it refers foo_instanceto the same instance as it *some_vector[0]does, but I cannot do this ...

  • I do not want to know if the two copies are equal; I want to check if the variables point to the same instance in memory

Can this be done?

+4
source share
1 answer

I did something on Rust GitHub and found out that there was a function for this instd , but it is not so anymore. There is an open RFC to return it.

Now you can stream to *const T:

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

, .

+8

Source: https://habr.com/ru/post/1654423/


All Articles