与借阅检查者和词汇生命周期作斗争

时间:2018-06-10 19:18:39

标签: rust borrow-checker

我正在尝试在树状数据结构中构建从根节点到叶节点的路径。该路径由对节点的可变引用的数组(path)表示:

fn build_path(&mut self, index: Index, shift: Shift) {
    debug_assert!(shift.0 >= BITS_PER_LEVEL);

    let mut path: [Option<&mut Node<T>>; MAX_HEIGHT] = new_path!();
    let mut path_i = 0;

    let mut node = self;
    let mut shift = shift;

    while shift.0 != BITS_PER_LEVEL {
        let cnode = node;

        let child = match *cnode {
            Node::Leaf { .. } => unreachable!(),
            Node::RelaxedBranch { .. } => unreachable!(),
            Node::Branch { ref mut children, len: _ } => {
                let i = index.child(shift);
                children[i].as_mut().unwrap()
            }
        };

        path[path_i] = Some(cnode);
        path_i = path_i + 1;

        node = Arc::make_mut(child);
        shift = shift.dec();
    }
}

借用检查程序吐出编译错误:

error[E0499]: cannot borrow `*cnode` as mutable more than once at a time
   --> src/main.rs:108:33
    |
102 | Node::Branch { ref mut children, len: _ } => {
    |                ---------------- first mutable borrow occurs here
...
108 | path[path_i] = Some(cnode);
    |                     ^^^^^ second mutable borrow occurs here
...
113 | }
    | - first borrow ends here

我该如何处理这个问题?我尝试了各种解决方法,但不幸的是,它们都没有工作。

编辑#1

以下是带有可执行代码段的防锈操场的链接:https://play.rust-lang.org/?gist=0e2a208a5fe5472229db30ac3d44c60d&version=nightly&mode=debug

编辑#2

我只想强调,迭代数据结构本身不是问题。我想要实现的是拥有一个对树节点的可变引用的数组(请参阅build_path方法中的变量路径)。

0 个答案:

没有答案