首页 > 解决方案 > Rust 赋值和使用借用同时

问题描述

让我感到困惑的是 line 的错误与 lineA有什么关系C,因为它们基本上出现在不同的分支中?

pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>
}

pub fn foo(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut p1 = head.as_mut()?;
    
    if let Some(p2) = p1.next.as_mut() {
        if true {
            p1.next = None; // A: Error here if C is not commented out 
        } else {
            // p1.next = None; // B
            p1 = p2; // C: No error on this line
        }
    }
    head

更糟糕的是,错误代码为 E0506,表明尝试分配借用值 ( p1.next)。为什么我现在不能分配这个借来的值(我相信它是可变借来的),但我可以通过删除 line 来做到这一点C

error[E0506]: cannot assign to `p1.next` because it is borrowed
  --> src/remove_dup.rs:11:13
   |
9  |     if let Some(p2) = p1.next.as_mut() {
   |                       ------- borrow of `p1.next` occurs here
10 |         if true {
11 |             p1.next = None; // A: Error happnens here if C is not commented out 
   |             ^^^^^^^
   |             |
   |             assignment to borrowed `p1.next` occurs here
   |             borrow later used here

标签: rustborrow-checker

解决方案


推荐阅读