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
1.0k views
in Technique[技术] by (71.8m points)

rust - Is there a way to distinguish between different `Rc`s of the same value?

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

2017 stabilization update (in 2020).

In Rust 1.17 and forward, you can use Rc::ptr_eq. It does the same as ptr::eq, without the need of converting the Rc to a reference or pointer.

Reference Equality

As the other answers mention Rc::ptr_eq (and ptr::eq) checks for reference equality, i.e. whether the two references "point" to the same address.

let five = Rc::new(5);
let same_five = Rc::clone(&five);
let other_five = Rc::new(5);

// five and same_five reference the same value in memory
assert!(Rc::ptr_eq(&five, &same_five));

// five and other_five does not reference the same value in memory
assert!(!Rc::ptr_eq(&five, &other_five));

The example is from the Rust Rc::ptr_eq docs.

Value Equality

Rc implements PartialEq, so simply use == as always, to perform value equality, i.e. whether the values are equal, irrelevant of whether they reference the same address in memory.

use std::rc::Rc;

let five = Rc::new(5);
let other_five = Rc::new(5);

let ten = Rc::new(10);

assert!(five == other_five);

assert!(ten != five);
assert!(ten != other_five);

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

...