在 Rust 中释放借用

Release borrowing in Rust

我正在尝试 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

如何从“y-借用”释放x

这是目前 Rust 借用检查器的一个限制,通常称为“非词法生命周期”(NLL)。这里的问题是,当您将引用分配给变量 (let mut y = &mut x;) 时,引用必须在变量的整个范围内有效。这意味着“x is borrowed”在 y 的整个范围内持续。所以编译器不关心行 y = &mut a;!

您可以阅读更多关于此的(技术)讨论 here at the tracking issue

编辑:非词法生命周期已在一段时间前登陆,因此您的代码现在应该可以正常编译了。