How to check if two variables point to the same ob

2020-01-29 01:46发布

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?

1条回答
再贱就再见
2楼-- · 2020-01-29 01:52

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.

查看更多
登录 后发表回答