Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example:

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);
}
  1. I want to check if foo_instance references the same instance as *some_vector[0], but I can't do this ...

  2. I don't want to know if the two instances are equal; I want to check if the variables point to the same instance in the memory

Is it possible to do that?

like image 816
Vasyl Bratushka Avatar asked Sep 13 '16 06:09

Vasyl Bratushka


People also ask

Can multiple variable reference a same object in memory?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

Can two variables have same address in memory?

Ya with reference variables you can make the parameter variable reside at the same address as the argument variable.

Which operators can be used to determine whether two variables are referring to the same object or not?

The Is Operator returns True if the objects are identical, and the IsNot Operator returns True if they are not.

Does the IS operator check whether they have same object?

Two objects having equal values are not necessarily identical. Put simply: == determines if the values of two objects are equal, while is determines if they are the exact same object.


1 Answers

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.

like image 185
ljedrz Avatar answered Sep 16 '22 16:09

ljedrz