What is the paradigmatic way to create a Rust tree with a parent pointer? [duplicate]

不羁岁月 提交于 2020-01-15 06:31:06

问题


I need to define a binary search tree where each node has access to the parent:

enum Tree<'a> {
    Leaf,
    Node {
        left: Box<Tree<'a>>,
        right: Box<Tree<'a>>,
        parent: &'a Tree<'a>,
        data: u64,
    }
}

impl <'a> Tree<'a> {
    pub fn new(data: u64, parent: &'a Tree) -> Tree<'a> {
        Tree::Node {
            left: Box::new(Tree::Leaf),
            right: Box::new(Tree::Leaf),
            parent,
            data
        }
    }
    pub fn insert_at_left_leaf(&'a mut self, data: u64) {
        match *self {
            Tree::Leaf => panic!("Leaf has no children"),
            Tree::Node {ref mut left, ..} => {
                **left = Tree::new(data, self);
            }
        }
    }
}

fn main() {
    let parent = Tree::Leaf;
    let mut t = Tree::Node {
        left: Box::new(Tree::Leaf),
        right: Box::new(Tree::Leaf),
        parent: &parent,
        data: 1u64
    };
    t.insert_at_left_leaf(2);
}

playground

However, I get the following compilation error:

error[E0502]: cannot borrow `*self` as immutable because `self.left` is also borrowed as mutable
  --> src/main.rs:24:42
   |
23 |             Tree::Node {ref mut left, ..} => {
   |                         ------------ mutable borrow occurs here
24 |                 **left = Tree::new(data, self);
   |                                          ^^^^ immutable borrow occurs here
25 |             }
26 |         }
   |         - mutable borrow ends here

What is the paradigmatic way to do this in safe Rust? Specifically, when I insert a new node as the leaf of an existing node, I do not want to re-allocate space for it. There is already space allocated for the Leaf and I want to simply overwrite it with the new node.

来源:https://stackoverflow.com/questions/45108489/what-is-the-paradigmatic-way-to-create-a-rust-tree-with-a-parent-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!