实现说明
Rc 与 RefCell 共享树节点可以归结为函数 new、push_child、child_count、main。
使用要点
- 演示输出是带标签的(
root children:、leaf strong count:),每个操作都会留下自己的一行标注。 - 执行文件,
main会按顺序走完new、push_child、child_count。
常见问题
运行「Rc 与 RefCell 共享树节点」会打印什么?
运行文件本身,root children:、leaf strong count: 这些前缀各对应一段演示逻辑。
入口签名:fn new(name: &str) -> Rc<Node>
核心语句
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()
}
代码示例
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);
}