fn main()
{
let node_x = TreeNode { name : "parent".to_owned(), children : RefCell::new(vec![]), parent : RefCell::new(None) };
let node_y = TreeNode { name : "child".to_owned(), children : RefCell::new(vec![]), parent : RefCell::new(None) };
let node_x = Rc::new(node_x);
let node_y = Rc::new(node_y);
node_x.add_child(node_y);
}
... I would like to simultaneously set its new parent (i.e., self). However, Rc pointer can either be cloned from the existing one (i.e., node_x) or created from scratch using Rc::new() that requires passing ownership of self inside add_child.
I believe there is no way to solve this problem with the current design. What other design strategies could be suggested to make this kind of tree/node API working?
Actually, you can pass self not as reference &self but as Rc<Self>, allowing you to call self.clone() to create a new Rc instance to your parent node you can pass to your child:
But you can trivially clone the Rc before passing it to the method… (or take an &Rc and clone inside, but that's not idiomatic because it forces the clone.)
Note that parent pointers are fundamentally a bit of a mess for ownership. If you can avoid them, you'll make your life much easier. (And you'll be able to share subtrees as well!)
Note that this will create a cycle between Rcs which you'll have to manually break or it will leak memory (no node of the tree will ever be dropped thus deallocated). To fix this you can use Weak for the parent instead of Option<Rc>