问题
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