不能在循环中多次借用可变错误 [英] Cannot borrow as mutable more than once error in a loop

查看:39
本文介绍了不能在循环中多次借用可变错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 leetcode 问题 #83从排序列表中删除重复项",但我被这个借用检查器问题困住了.

I am working on leetcode problem #83 "Remove Duplicates from Sorted List", but I'm stuck on this borrow checker issue.

ListNode 结构由问题给出,因此无法更改.我已经尝试重组循环和 if 语句,但我还没有找到可行的解决方案.

The ListNode struct is given by the problem so it cannot be changed. I have tried restructuring the loop and if statement, but I haven't found a working solution.

我想做什么:

// Definition for singly-linked list.
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }
}

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                continue;
            }
        }
        cursor = &mut c.next;
    }
    list
}

我得到的错误:

error[E0499]: cannot borrow `*cursor` as mutable more than once at a time
  --> src/lib.rs:17:25
   |
17 |     while let Some(c) = cursor.as_mut() {
   |                         ^^^^^^ mutable borrow starts here in previous iteration of loop

似乎显示相同错误的简化代码:

Simplified code that seems to show the same error:

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if c.val > 0 {
            cursor = &mut c.next;
        }
    }
    list
}

我不明白为什么在循环的下一次迭代之前没有删除可变借用.这似乎是由有条件地更改游标引起的,但我不明白为什么会阻止借用被删除.

I don't understand why the mutable borrow hasn't been dropped before the next iteration of the loop. It seems to be caused by conditionally changing the cursor, but I don't see why that would prevent the borrow from being dropped.

推荐答案

这是我最终得到的解决方案.在 if 语句中重新分配 cursor 可以解决问题.

Here's the solution I ended up with. Reassigning cursor in the if statement fixes the problem.

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = list.as_mut();
    while let Some(c) = cursor {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                cursor = Some(c);
                continue;
            }
        }
        cursor = c.next.as_mut();
    }
    list
}

这篇关于不能在循环中多次借用可变错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆