Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

pointers - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...