Sadly there isn't. Rust is sometimes overly verbose, but that's the price to pay for such a precise level of control. The other way around would be even more verbose:
Hypothetical Rust where all closures would be move
Rust could have chosen to make all closures be move
, but then non-move
closures would become even more cumbersome to write (compared to just writing move
for a move
closure), and this in turn would make the language even harder for novices:
Example
- Imagine having a non-
Copy
variable around, such as a String
,
use ::std::{
fs::File,
io::Write,
};
fn foo (filename: String)
{
let mut file =
File::create(&filename)
.unwrap_or_else(|err| panic!(
"Failed to create {:?}: {}", &filename, err,
))
;
let contents = "Hello, World!";
file.write_all(contents.as_bytes())
.unwrap_or_else(|err| panic!(
"Failed to write {:?} into {:?}: {}",
contents, &filename, err,
))
;
filename
}
which would error with:
error[E0382]: use of moved value: `filename`
--> src/lib.rs:16:25
|
6 | fn foo (filename: String)
| -------- move occurs because `filename` has type `std::string::String`, which does not implement the `Copy` trait
...
10 | .unwrap_or_else(|err| panic!(
| ---------- value moved into closure here
11 | "Failed to create {:?}: {}", &filename, err,
| --------- variable moved due to use in closure
...
16 | .unwrap_or_else(|err| panic!(
| ^^^^^^^^^^ value used here after move
17 | "Failed to write {:?} into {:?}: {}",
18 | contents, &filename, err,
| --------- use occurs due to use in closure
And fixing it would require writing non-move
closures as follows:
use ::std::{
fs::File,
io::Write,
};
fn foo (filename: String)
{
let mut file =
File::create(&filename)
.unwrap_or_else({
let filename = &filename;
|err| panic!(
"Failed to create {:?}: {}", filename, err,
)
})
;
let contents = "Hello, World!";
file.write_all(contents.as_bytes())
.unwrap_or_else({
let filename = &filename;
|err| panic!(
"Failed to write {:?} into {:?}: {}",
contents, filename, err,
)
})
;
}