【发布时间】:2020-03-29 19:56:15
【问题描述】:
How do I express mutually recursive structures in Rust? 解释了如何表示类似图的结构,但没有解释如何遍历图(只是为了添加更多的子节点)。我尝试适应的Rc<RefCell<T>> 解决方案没有编译。
我正在寻找一种在安全 Rust 中设计和遍历类图结构的方法,利用 Rc<T> 和/或 RefCell<T> 实现内部可变性。由于&mut T 别名规则,我当前的Node 无法编译:
struct Node {
parent: Option<&mut Node>, // a mutable reference to the Node's owner
children: Vec<Node>, // each Node owns its children
}
impl Node {
fn add_child(&mut self, x: Node) {
self.children.push(x);
}
fn get_child(&mut self, i: usize) -> &mut Node {
&mut self.children[i]
}
fn get_parent(&mut self) -> &mut Node {
self.parent.expect("No parent!")
}
}
示例功能:
let mut top_node = Node::new(None);
let mut ptr = &mut top_node;
ptr.add_child(Node::new(&mut ptr)); // add a child to top_node
ptr = ptr.get_child(0); // walk down to top_node's 0th child.
ptr = ptr.get_parent(); // walk back up to top_node
我反复重写了这个实现,用Rc、Weak、RefCell 和RefMut 的组合替换了&mut T,但无济于事。我对底层内存管理了解不够。
有更多使用内部可变性经验的人能否解释一下如何正确设计和遍历此图?
【问题讨论】:
-
这是一个很好的资源,可以帮助您解决问题。它在链表的上下文中解释了这个确切的问题,以及在制作这些类型的数据结构时容易落入的一些其他陷阱。 rust-unofficial.github.io/too-many-lists/index.html
标签: data-structures rust