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.
If you can use Rust version 1.31 or later, then just specify the edition in your Cargo.toml
:
[package]
edition = "2018"
If you are using the latest Rust, this will be put there automatically when you create a new crate with cargo new
.
If you are not using Cargo, rustc
defaults to Edition 2015, so you need to explicitly provide the edition:
rustc --edition 2018 main.rs
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);