锈错误:掉落可变借位后发生借位 [英] Rust error: borrow occurs after drop a mutable borrow

查看:91
本文介绍了锈错误:掉落可变借位后发生借位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试代码:

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之前被手动删除的,不是吗?

But inc is dropped manually before println! borrow c, isn't it?

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

So what's the problem with my code? Please help.

推荐答案

您对范围和生命周期的工作方式的理解是正确的.在Rust Edition 2018中,默认情况下它们启用了非词汇生存期.在此之前,inc的生存期将一直到当前词法作用域的末尾(即块的末尾),即使其值已移到该词法作用域之前.

Your understanding of how scopes and lifetimes work is correct. In Rust Edition 2018, they enabled non-lexical lifetimes by default. Prior to that, the lifetime of inc would have been to the end of the current lexical scope (i.e. the end of the block) even though its value was moved before that.

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

If you can use Rust version 1.31 or later, then just specify the edition in your Cargo.toml:

[package]
edition = "2018"

如果您使用的是最新的Rust,则使用cargo new创建新的板条箱时,它将自动放置在此处.

If you are using the latest Rust, this will be put there automatically when you create a new crate with cargo new.

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

If you are not using Cargo, rustc defaults to Edition 2015, so you need to explicitly provide the edition:

rustc --edition 2018 main.rs


如果由于某种原因您使用的是每晚更晚的Rust版本,则可以通过在主文件中添加以下内容来启用非词法生存期:


If you are using an older nightly build of Rust for some reason, then you can enable non-lexical lifetimes by adding this in your main file:

#![feature(nll)]

如果您使用的是较旧的发行版,通常可以使用如下代码块,通过引入较短的作用域来解决这些错误:

If you are stuck on an older release build, you can usually fix these errors by introducing a shorter scope, using a block like this:

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

这篇关于锈错误:掉落可变借位后发生借位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆