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?