我正在尝试学习 rust internal mutability 的一些基本概念。并尝试实现一个树状数据结构示例:
-
- 每个节点都有一个父节点。
-
- 每个节点都有一些子节点。
-
- 从每个节点我可以更改父节点和所有子节点,不仅是节点的数量,还有一些节点属性。
-
- 没有循环参考问题。
我写的代码列表如下,但有点难看,可能有一些性能问题。所以问题是如何提高代码质量。欢迎任何建议。
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Weak;
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<RefCell<Node>>>,
children: RefCell<Vec<Rc<RefCell<Node>>>>,
}
fn main() {
let leaf = Rc::new(RefCell::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
}));
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf),
);
{
let branch = Rc::new(RefCell::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
}));
*(*leaf).borrow_mut().parent.borrow_mut() = Rc::downgrade(&branch);
// try to change parent data attribute from leaf
(*(*(*(*leaf).borrow_mut().parent.borrow_mut()).upgrade().unwrap()).borrow_mut()).value = 20 ;
println!("branch value change to : {:?}", branch.borrow().value);
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch),
);
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf),
);
}
println!("leaf parent = {:?}", (*leaf).borrow_mut().parent.borrow_mut().upgrade());
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf),
);
}
输出是:
leaf strong = 1, weak = 0
branch value change to : 20
branch strong = 1, weak = 1
leaf strong = 2, weak = 0
leaf parent = None
leaf strong = 1, weak = 0