在Rust中释放借用

7

我正在尝试使用Rust语言,但不太理解"borrowing"(借用)的概念。

fn main() {
    let mut x = 10;
    let mut a = 6;
    let mut y = &mut x;

    *y = 6;
    y = &mut a;

    x = 15;
    println!("{}", x);
}

我遇到了一个错误:

error[E0506]: cannot assign to `x` because it is borrowed
 --> <anon>:9:5
  |
4 |     let mut y = &mut x;
  |                      - borrow of `x` occurs here
...
9 |     x = 15;
  |     ^^^^^^ assignment to borrowed `x` occurs here

error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
  --> <anon>:10:20
   |
4  |     let mut y = &mut x;
   |                      - mutable borrow occurs here
...
10 |     println!("{}", x);
   |                    ^ immutable borrow occurs here
11 | }
   | - mutable borrow ends here

我该如何将变量x从"y借用"中释放?

1
你只需要开始以作用域思考 - E net4
1个回答

5
这是 Rust 借用检查器目前的限制,通常称为“非词法生命周期”(NLL)。问题在于,当您将引用分配给变量(let mut y = &mut x;)时,该引用必须对整个变量的范围有效。这意味着“x 被借用”的持续时间为 y 的整个范围。因此,编译器不关心行 y = &mut a;!您可以在此处的跟踪问题中阅读更多(技术)讨论。
编辑:非词法生命周期已经实现,所以您的代码现在应该能够编译成功。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接