Rust error: borrow occurs after drop a mutable borrow

Rust error: borrow occurs after drop a mutable borrow

我的测试代码:

let mut c = 0;
let mut inc = || { c += 1; c };
drop(inc);
println!("{}", c);

rustc 说:

error[E0502]: cannot borrow `c` as immutable because it is also borrowed as mutable
  --> .\src\closure.rs:20:24
   |
12 |         let mut inc = || { c += 1; c };
   |                       --   ----- previous borrow occurs due to use of `c` in closure
   |                       |
   |                       mutable borrow occurs here
...
20 |         println!("{}", c);
   |                        ^^^^^ immutable borrow occurs here
21 |     }
   |     - mutable borrow ends here

但是 inc 是在 println! 借用 c 之前手动删除的,不是吗?

那么我的代码有什么问题?请帮忙。

您对作用域和生命周期如何工作的理解是正确的。在 Rust Edition 2018 中,他们默认启用了非词法生命周期。在此之前,inc 的生命周期将一直到当前词法范围的末尾(即块的末尾),即使它的值在此之前被移动。

如果您可以使用 Rust 版本 1.31 或更高版本,那么只需在 Cargo.toml:

中指定版本
[package]
edition = "2018"

如果您使用的是最新的 Rust,当您使用 cargo new.

创建新的 crate 时,它​​会自动放在那里

如果您不使用 Cargo,rustc 默认为 2015 版,因此您需要明确提供版本:

rustc --edition 2018 main.rs

如果您出于某种原因使用较旧的 Rust 每晚构建,那么您可以通过在主文件中添加以下内容来启用非词法生命周期:

#![feature(nll)]

如果您停留在较旧的版本上,通常可以通过引入更短的范围来修复这些错误,使用这样的块:

let mut c = 0;
{
    let mut inc = || { c += 1; c };
    drop(inc);
    // scope of inc ends here
}
println!("{}", c);