可变二叉树上的递归:`已经借用:BorrowMutError`

Jon*_*ght 1 memory-management rust borrowing

我从一个Vec已排序的节点开始,然后使用此排序将这些节点在二叉树中链接在一起,然后返回基本结构

// Test name
#[derive(Clone)]
struct Struct {
    parent: Option<Rc<RefCell<Struct>>>,
    superscript: Option<Rc<RefCell<Struct>>>,
    subscript: Option<Rc<RefCell<Struct>>>,
    height: u32,
    center: u32,
    symbols: VecDeque<u8>
}
Run Code Online (Sandbox Code Playgroud)

最终得到由上述 s 形成的二叉树Struct。此时,这些Structs 是唯一拥有的,所以我认为我可以从 using 转换Rc<RefCell<Struct>>RefCell<Struct>(认为Box<Struct>由于内部可变性而不起作用?),但我不确定这如何或是否有助于解决我遇到的问题。

之后,我需要以一种新颖的方式迭代 s Struct,并通过调用 来改变整个递归过程中symbols属于各个s 的各种内容。Struct.pop_front()

我当前的实现这样做会导致thread 'main' panicked at 'already borrowed: BorrowMutError'.

游乐场链接:https://play.rust-lang.org/? version=stable&mode=debug&edition=2018&gist=636c93088f5a431d0d430d42283348f3

它的功能(请原谅复杂的逻辑):

fn traverse_scripts(row: Rc<RefCell<Struct>>) {
    if let Some(superscript_row) = &row.borrow().superscript {
        if let Some(superscript_symbol) = superscript_row.borrow().symbols.front() {
            if let Some(current_row_symbol) = row.borrow().symbols.front()  {
                if superscript_symbol < current_row_symbol {
                    println!("^{{{}",*superscript_symbol);
                    superscript_row.borrow_mut().symbols.pop_front();
                    traverse_scripts(Rc::clone(superscript_row));
                }
            }
            else {
                println!("^{{{}",*superscript_symbol);
                superscript_row.borrow_mut().symbols.pop_front();
                traverse_scripts(Rc::clone(superscript_row));
            }
        }
    }

    if let Some(subscript_row) = &row.borrow().subscript {
        if let Some(subscript_symbol) = subscript_row.borrow().symbols.front() {
            if let Some(current_row_symbol) = row.borrow().symbols.front() {
                if subscript_symbol < current_row_symbol  {
                    print!("_{{{}",*subscript_symbol);
                    subscript_row.borrow_mut().symbols.pop_front();
                    traverse_scripts(Rc::clone(subscript_row));
                }
            }
            else {
                print!("_{{{}",*subscript_symbol);
                subscript_row.borrow_mut().symbols.pop_front();
                traverse_scripts(Rc::clone(subscript_row));
            }
        }
    }

    if let Some(current_row_symbol) = row.borrow().symbols.front()  {
        if let Some(parent_row) = &row.borrow().parent {
            if let Some(parent_symbol) = parent_row.borrow().symbols.front() {
                if current_row_symbol < parent_symbol {
                    print!(" {}",*current_row_symbol);
                    row.borrow_mut().symbols.pop_front();
                    traverse_scripts(Rc::clone(&row));
                }
            }
        }
        else {
            print!(" {}",*current_row_symbol);
            row.borrow_mut().symbols.pop_front();
            traverse_scripts(Rc::clone(&row));
        }
    }

    if let Some(parent_row) = &row.borrow().parent {
        if let Some(parent_symbol) = parent_row.borrow().symbols.front() {
            print!("}} {}",*parent_symbol);
            row.borrow_mut().symbols.pop_front();
            traverse_scripts(Rc::clone(parent_row));
        } else {
            print!("}}");
            traverse_scripts(Rc::clone(parent_row));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我考虑过使用它Arc<Mutex<Struct>>来代替遍历,但鉴于它不是多线程的,我认为没有必要?

我想我可能在这里缺少一个相对简单的想法,我真的很感激任何帮助。

如果我在问题中遗漏了任何内容,请发表评论,我会尝试添加它。

tre*_*tcl 5

当您在a上调​​用borrow或时,会创建一个保护对象(或),只要内部值存在,它就授予对内部值的访问权限。这个守卫将锁定它,直到它超出范围并被摧毁。让我们看一下其中的一部分:borrow_mutRefCellRefRefMutRefCelltraverse_scripts

if let Some(superscript_row) = &row.borrow().superscript { // row is borrowed
    if let Some(superscript_symbol) = superscript_row.borrow().symbols.front() { // superscript_row is borrowed
        if let Some(current_row_symbol) = row.borrow().symbols.front() { // row is borrowed again
            if superscript_symbol < current_row_symbol {
                println!("^{{{}", *superscript_symbol);
                superscript_row.borrow_mut().symbols.pop_front(); // superscript_row is borrowed mutably (ERROR)
                traverse_scripts(Rc::clone(superscript_row)); // recursive call while row and superscript_row are borrowed (ERROR)
            }
        } else {
            println!("^{{{}", *superscript_symbol);
            superscript_row.borrow_mut().symbols.pop_front(); // superscript_row is borrowed mutably (ERROR)
            traverse_scripts(Rc::clone(superscript_row)); // recursive call while row and superscript_row are borrowed (ERROR)
        } // row is no longer borrowed twice
    } // superscript_row is no longer borrowed
} // row is no longer borrowed
Run Code Online (Sandbox Code Playgroud)

例如,在第一行中,row.borrow()返回一个Ref<Struct>. 这Ref不能立即删除,因为它是在if let主体期间被 借用的superscript_row。所以它一直保持活力——直到决赛}

这对于递归调用来说是一个问题traverse_scripts,因为在整个Struct递归调用过程中 是被借用的。任何在调用堆栈中更深入地借用相同的可变内容的尝试都将失败。(一成不变地借用它仍然有效。)Struct

第二行superscript_row是借用的。这有同样的问题,但它还有一个更直接的问题:它稍后在同一函数中可变地借用,甚至在递归调用之前。这borrow_mut永远不会成功,因为superscript_row那时总是已经借用了。

为了解决这两个问题,我们将做两件事:

  1. 将每个ReforRefMut保护存储在其自己的变量中并重新使用该保护,而不是再次在同一变量上调用borrow()or 。borrow_mut()
  2. 在递归之前,drop每个仍然活着的守卫都不会在递归调用中借用任何东西。

该部分可能重写如下:

{ // This scope will constrain the lifetime of row_ref
    let row_ref = row.borrow();
    if let Some(superscript_row) = &row_ref.superscript {
        let mut child = superscript_row.borrow_mut(); // use borrow_mut here because we know we'll need it later
        if let Some(superscript_symbol) = child.symbols.front() {
            if let Some(current_row_symbol) = row_ref.symbols.front() {
                if superscript_symbol < current_row_symbol {
                    println!("^{{{}", *superscript_symbol);
                    child.symbols.pop_front();
                    drop(child); // child is no longer needed, so drop it before recursing
                    // Since superscript_row borrows from row_ref, we must Rc::clone it before
                    // dropping row_ref so that we can still pass it to traverse_scripts.
                    let superscript_row = Rc::clone(superscript_row);
                    drop(row_ref); // row_ref is no longer needed, so drop it before recursing
                    traverse_scripts(superscript_row);
                }
            } else {
                println!("^{{{}", *superscript_symbol);
                child.symbols.pop_front();
                // see comments earlier
                drop(child);
                let superscript_row = Rc::clone(superscript_row);
                drop(row_ref);
                traverse_scripts(superscript_row);
            }
        }
    } // child is dropped here (if it wasn't already). superscript_row is no longer borrowed
} // row_ref is dropped here (if it wasn't already). row is no longer borrowed
Run Code Online (Sandbox Code Playgroud)

全节目游乐场

这看起来很复杂,因为它很复杂。在改变数据结构的同时遍历数据结构是错误的常见来源(在大多数语言中,不仅仅是 Rust)。至少看起来,traverse_scripts需要突变的唯一原因是调用pop_fronton symbols,因此,如果您可以重新设计数据结构,使得 only symbolsis in a RefCell,则可以仅使用引用进行遍历&,这会容易得多。另一种常见的方法是编写返回新数据结构的函数,而不是就地改变它们。