Hi,
let's say I have type T, and below persudo codes
struct T { val: i32 };
impl T {
fn compare(&self, other: Rc<RefCell<T>>) {
//how to compare `self` is the same object as T in `other`???
}
}
let t = T {val: 1};
let x = Rc::new(RefCell::new(t));
let y = x.clone();
x.borrow().compare(y); // is it feasible to do
If you only want to compare Rc<RefCell<T>> with another Rc<RefCell<T> (which is shown in the pseudo code you shared), you can compare them directly with each other, thanks to these two implementations of PartialEq for Rc and RefCell. If you want to compare T with Rc<RefCell<T> (which you ask in your title), you'd have to get a reference &T to the value stored in the RefCell with *x.borrow().
Here example code:
use std::cell::RefCell;
use std::rc::Rc;
#[derive(PartialEq, Debug, Clone)]
struct Foo {
val: i32,
}
fn main() {
let t = Foo { val: 1 };
let not_t = Foo { val: 2 };
let x = Rc::new(RefCell::new(t.clone()));
let y = x.clone();
// comparing Rc<RefCell<T>> with each other directly
assert_eq!(x, y);
assert_eq!(x, Rc::new(RefCell::new(t.clone()))); // compares by value, not by location in memory
// comparing T with Rc<RefCell<T>>
assert_eq!(t, *x.borrow());
assert_ne!(not_t, *y.borrow());
}
Note: I usually associate compare with sorting/ordering so your naming is unexpected. Also, generally equality is by value, so I suggest being really obvious about the naming like ptr_eq unless the Rc is private and the instance mattering is inherent.