Shared Tree Nodes Rc RefCell

Let several parents share child nodes through Rc<RefCell<Vec>>: Rc clones share ownership without copying, RefCell mutates inside an immutable shell.

RustData Integrity

Code

rustsnippet
39 lines
use std::cell::RefCell;
use std::rc::Rc;

type Children = Rc<RefCell<Vec<Rc<Node>>>>;

#[derive(Debug)]
struct Node {
    name: String,
    children: Children,
}

impl Node {
    // Rc + RefCell = shared mutable tree nodes
    fn new(name: &str) -> Rc<Node> {
        Rc::new(Node { name: name.into(), children: Rc::new(RefCell::new(vec![])) })
    }

    fn push_child(self: &Rc<Self>, child: Rc<Node>) {
        // RefCell 允许在不可变 Rc 外壳内就地修改孩子列表
        self.children.borrow_mut().push(child);
    }

    fn child_count(&self) -> usize {
        self.children.borrow().len()
    }
}

fn main() {
    let root = Node::new("root");
    let leaf = Node::new("leaf");

    // Rc::clone 只增加强引用计数,不复制节点本身
    root.push_child(Rc::clone(&leaf));
    root.push_child(Node::new("second"));

    println!("root children: {}", root.child_count());
    println!("leaf strong count: {}", Rc::strong_count(&leaf));
    println!("{:?}", root);
}

Inside the snippet

The snippet is organized around the functions new, push_child, child_count and main.

Caveats

  • There is no dependency tree here — the platform is the whole dependency.

Putting it to use

Entry signature: fn new(name: &str) -> Rc<Node>

Look for the root children:, leaf strong count: prefixes when the file runs; they tie each line to its step.

main is the driver: it invokes new, push_child and child_count before returning.

Core lines

fn push_child(self: &Rc<Self>, child: Rc<Node>) {
// RefCell 允许在不可变 Rc 外壳内就地修改孩子列表
self.children.borrow_mut().push(child);
}
fn new(name: &str) -> Rc<Node> {
Rc::new(Node { name: name.into(), children: Rc::new(RefCell::new(vec![])) })
}
fn child_count(&self) -> usize {
self.children.borrow().len()
}

Interactive Tools for This Topic

FAQ

What does Shared Tree Nodes Rc RefCell print when run?
Invoke the file as-is — the `root children:`, `leaf strong count:` prefixes identify which step printed each line.