如何可变地借用递归数据结构?

时间:2020-05-19 17:40:53

标签: recursion rust borrow

上下文

我正在基于Rust的Rust中构建一个GUI库。小部件可以具有子级小部件。这样,小部件将存储为树。我希望能够从此树中可变地借用一个小部件。

示例

为简化起见,这是一个基于多态链表的可重现的最小示例,在该示例中,我尝试编写一个仅使用.get_next_mut()方法(playground)获得最后一个元素的函数:

trait ListNode {
    // mutably borrows the next element of this node
    fn get_next_mut(&mut self) -> Option<&mut dyn ListNode>;
}

// recursively get the next element until the last one is met, then returns it
fn get_last_mut(node: &mut dyn ListNode) -> &mut dyn ListNode {
    match node.get_next_mut() {
        Some(next) => get_last_mut(next),
        None => node,
    }//         ^^^^ cannot borrow `*node` as mutable more than once at a time
}

此代码无效,因为编译器认为node仍是从node.get_next_mut()借来的。

解决

我尝试使用this solution进行修复,但问题仍然存在

fn get_last_mut(mut node: &mut dyn ListNode) -> &mut dyn ListNode {
    loop {
        let tmp = node;
        if let Some(child) = tmp.get_next_mut() {
            node = child;
        }
        else {
            node = tmp;
            //     ^^^ cannot borrow `*tmp` as mutable more than once at a time
            break;
        }
    }
    node
}

0 个答案:

没有答案
相关问题