Is there a way to distingush between different `Rc`s of the same value?

試著忘記壹切 提交于 2020-01-24 10:14:45

问题


Here's an example:

use std::rc::Rc;

#[derive(PartialEq, Eq)]
struct MyId;

pub fn main() {
    let rc_a_0 = Rc::new(MyId);
    let rc_a_1 = rc_a_0.clone();
    let rc_b_0 = Rc::new(MyId);
    let rc_b_1 = rc_b_0.clone();

    println!("rc_a_0 == rc_a_1: {:?}", rc_a_0 == rc_a_1);
    println!("rc_a_0 == rc_b_0: {:?}", rc_a_0 == rc_b_0);
}

Both println!s above print true. Is there a way distinguish between the rc_a_* and rc_b_* pointers?


回答1:


You can cast &*rc to *const T to get a pointer to the underlying data and compare the value of those pointers:

use std::rc::Rc;

#[derive(PartialEq, Eq)]
struct MyId;

pub fn main() {
    let rc_a_0 = Rc::new(MyId);
    let rc_a_1 = rc_a_0.clone();
    let rc_b_0 = Rc::new(MyId);
    let rc_b_1 = rc_b_0.clone();

    println!(
        "rc_a_0 == rc_a_1: {:?}",
        &*rc_a_0 as *const MyId == &*rc_a_1 as *const MyId
    );
    println!(
        "rc_a_0 == rc_b_0: {:?}",
        &*rc_a_0 as *const MyId == &*rc_b_0 as *const MyId
    );
}

prints

rc_a_0 == rc_a_1: true
rc_a_0 == rc_b_0: false



回答2:


The same answer as Dogbert, but maybe a bit cleaner:

use std::ptr;

println!(
    "rc_a_0 == rc_a_1: {:?}",
    ptr::eq(rc_a_0.as_ref(), rc_a_1.as_ref())
);
println!(
    "rc_a_0 == rc_b_0: {:?}",
    ptr::eq(rc_a_0.as_ref(), rc_b_0.as_ref())
);
rc_a_0 == rc_a_1: true
rc_a_0 == rc_b_0: false

In short, you want reference equality, not value equality. A raw pointer's value is the memory address, so comparing the value of a raw pointer is equivalent to reference equality.

See also:

  • How to check if two variables point to the same object in memory?
  • Why can comparing two seemingly equal pointers with == return false?


来源:https://stackoverflow.com/questions/37706596/is-there-a-way-to-distingush-between-different-rcs-of-the-same-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!