【问题标题】:Release borrowing in Rust [duplicate]在 Rust 中释放借用 [重复]
【发布时间】:2017-04-20 15:19:59
【问题描述】:

我正在尝试 Rust,但在理解“借用”方面遇到了一些问题。

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-borrowing”释放x

【问题讨论】:

标签: rust borrow-checker


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多