Rc and tree-like structures

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:

use std::cell::RefCell;
use std::rc::Rc;

struct TreeNode {
    name: String,
    children: RefCell<Vec<Rc<TreeNode>>>,
    parent: RefCell<Option<Rc<TreeNode>>>,
}

impl TreeNode {
    pub fn set_parent(&self, parent: Rc<TreeNode>) {
        *self.parent.borrow_mut() = Some(parent);
    }

    pub fn add_child(self: Rc<Self>, child: Rc<TreeNode>) {
        self.children.borrow_mut().push(child.clone());
        child.set_parent(self.clone());
    }
}

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

Playground.

(I wasn't really aware that you could do this until this recent topic reminded me)