Why match returns reference?

enum List {
    Cons(i32, RefCell<Rc<List>>),

impl List {
    fn tail(&self) -> Option<&RefCell<Rc<List>>> {
        match self {
            Cons(_, item) => Some(item),
            Nil => None,

Here item of Some(item) is &RefCell<Rc>, why it's reference?

Because you're matching on &List. &self in function signature borrows the object, and makes self variable hold a reference.

Once something is behind a reference, you need to dereference it, e.g. match *self. Sometimes dereferencing is not even possible, because it'd mean taking ownership of something from a borrowed object (that's stealing!)

BTW, usually RefCell<Rc<T>> is used the other way: Rc<RefCell<T>>. You can clone &Rc to get non-temporary shared ownership: Rc.

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.