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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…