Given a T and Rc<RefCell<T>>, how to compare the T is the same data

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

other.borrow() gets you to the other inner value.

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());


Thanks, to clarify, My question is to compare it is same object aka location, not by value

That sounds like Rc::ptr_eq.

That's not the same thing as your compare function which is comparing a &T to an Rc<RefCell<T>> but maybe it's what you actually want?


Unfortunately not

Then I'm afraid it's unclear what you do want.


Sounds like you just want to check addresses?

 std::ptr::eq(self, &*other.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.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.