不能借一次错误的可变更为循环

问题描述 投票:1回答:1

我的工作本文给出了问题#83“从排序清单删除重复”,但我卡在此借检查问题。

该ListNode结构由该问题给出的,因此它不能被改变。我曾尝试重组循环和if语句,但我还没有找到一个有效的解决方案。

我所试图做的事:

// 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

简化代码,似乎表明了同样的错误:

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
}

我不明白为什么可变借尚未在循环的下一次迭代之前丢弃。这似乎是有条件改变光标引起的,但我不明白为什么会阻止借被丢弃。

rust borrow-checker
1个回答
0
投票

这是我结束了与解决方案。 if语句重新分配cursor解决了这个问题。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.