使用rust 错误 : borrow occurs after drop a mutable borrow

标签 rust lifetime 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 的生命周期将一直到当前词法范围的末尾(即 block 的末尾),即使它的值在此之前被移动。

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

[package]
edition = "2018"

如果您使用的是最新的 Rust,当您使用 cargo new 创建一个新的 crate 时,它​​会自动放在那里。


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

rustc --edition 2018 main.rs

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

#![feature(nll)]

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

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

关于使用rust 错误 : borrow occurs after drop a mutable borrow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503199/

相关文章:

string - 交替使用 str 和 String

rust - 难以管理引用和取消引用的组合

rust - 添加时对 i32 的不可变和可变引用有什么区别?

ruby - 安装 gem 时如何构建 Rust 库?

rust - 铁处理机 : Missing Lifetime Specifiers

string - 我如何制作格式!从条件表达式返回 &str?

asp.net-mvc-3 - controller 'TestController' 单个实例不能用于处理多个请求

rust - 当 Rust 中一个值覆盖另一个值时,堆栈上会发生什么?

rust - 为什么没有发生借用重叠时会出现借用错误?