【问题标题】:How to walk a mutually recursive graph in safe Rust?如何在安全的 Rust 中遍历相互递归图?
【发布时间】: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

我反复重写了这个实现,用RcWeakRefCellRefMut 的组合替换了&amp;mut T,但无济于事。我对底层内存管理了解不够。

有更多使用内部可变性经验的人能否解释一下如何正确设计和遍历此图?

【问题讨论】:

  • 这是一个很好的资源,可以帮助您解决问题。它在链表的上下文中解释了这个确切的问题,以及在制作这些类型的数据结构时容易落入的一些其他陷阱。 rust-unofficial.github.io/too-many-lists/index.html

标签: data-structures rust


【解决方案1】:

关键是使用混合 Arena/Cell 解决方案。父母和孩子现在只是对节点的引用,但是使用 CellRefCell 启用可变性:

struct Node<'a> {
    arena: &'a Arena<Node<'a>>,
    parent: Cell<Option<&'a Node<'a>>>,
    children: RefCell<Vec<&'a Node<'a>>>,
}

impl<'a> Node<'a> {
    fn add_child(&'a self) {
        let child = new_node(self.arena);
        child.parent.set(Some(self));
        self.children.borrow_mut().push(child);
    }
    fn get_child(&'a self, i: usize) -> &'a Node<'a> {
        self.children.borrow()[i]
    }
    fn get_parent(&'a self) -> &'a Node<'a> {
        self.parent.get().expect("No Parent!")
    }
}

现在,Arena 拥有每个节点,而不是父母拥有他们的孩子(这只是一个实现细节,不会妨碍任何功能)。结果,无需将父级传递给add_child

let arena: Arena<Node> = Arena::new();
let top_node = new_node(&arena);
top_node.add_child();

let mut ptr = top_node.get_child(0);

ptr.add_child();

ptr = ptr.get_child(0);
ptr = ptr.get_parent();

该解决方案使用以下辅助函数来启动和保持 Arena 的所有权:

fn new_node<'a>(arena: &'a Arena<Node<'a>>) -> &'a mut Node<'a> {
    arena.alloc(Node {
        arena: arena,
        parent: Cell::new(None),
        children: RefCell::new(vec![]),
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2016-06-02
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多