Auto derefing? Trying to understand behavior of Rc's and references

I am going through the Rust book, current at Adding a Reference from a Child to Its Parent

Quoting from the book:

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());

    let branch = Rc::new(Node {
        value: 5,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });

    *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}

The part that surprises me is this line:

*leaf.parent.borrow_mut() = Rc::downgrade(&branch);

The expression leaf.parent.borrow_mut() evaluates to a mutable reference, which I understand to be similar to a pointer in C/C++. So I get why I need to use the * dereference operator to change the value it points to. But isn't the expression on the right-hand side also equivalant to a reference/pointer? (It's a Weak reference). Why don't I have to use * on the right hand side of this assignment?

Because you're storing this Weak reference itself, not the object it points to. leaf.parent has type RefCell(Weak(Node)), by borrowing we get &mut Weak(Node), by dereferencing we get Weak(Node) - and that's exactly what you get from Rc::downgrade.

Thank you for walking me through that. That was helpful.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.