Sub topic 3
Taking ownership with move
This chapter assumes you know Rust ownership and borrowing, and that you have read how closures capture variables by shared borrow, mutable borrow, or move. Here you will see how the move keyword changes that choice and when you need it.
What move does
Without move, the compiler picks the lightest capture that the closure body allows. A closure that only reads a variable borrows it. Putting move before the parameter list overrides this. Every captured variable is moved into the closure, whatever the body does with it.
fn main() {
let name = String::from("Ada");
let greet = move || println!("Hello, {}", name);
greet();
greet();
// Using `name` here would be error E0382: value borrowed after move.
}The closure now owns name. Calling greet twice is fine because printing only needs a shared reference to the owned String.
Why threads need it
thread::spawn requires a closure that is 'static. That means it cannot hold references to the spawning function's local variables, because the thread might outlive them. If you omit move and the closure borrows a local, the compiler reports error E0373 ("closure may outlive the current function") and suggests adding move.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", data);
});
handle.join().unwrap();
}After the move, data belongs to the new thread. The main thread can no longer use it.
Copy types and clones
move copies values whose types implement Copy, such as integers. The original stays usable. For other types you can clone first and move the clone.
use std::thread;
fn main() {
let n = 5;
let add_n = move |x: i32| x + n;
println!("{}", add_n(1)); // 6
println!("{}", n); // 5, because i32 is Copy
let original = vec![1, 2, 3];
let copy = original.clone();
let handle = thread::spawn(move || println!("{:?}", copy));
handle.join().unwrap();
println!("{:?}", original); // still usable
}| Captured type | Without `move` | With `move` |
|---|---|---|
| `i32` (Copy) | Borrowed | Copied; original still usable |
| `String`, `Vec` | Borrowed | Moved; original unusable |
| `&T` reference | Reference copied | Reference copied |
move does not decide Fn, FnMut or FnOnce
move controls how values get into the closure. The closure body decides which trait it implements. A move closure that only reads its captured values still implements Fn, so you can call it many times, as greet did above. A closure that moves a captured value out of itself, for example by returning it, is FnOnce with or without move.
Common mistakes
- Using a variable after a
moveclosure took it. Clone before the closure, or capture a reference on purpose by creatinglet r = &data;and movingr. - Adding
moveto a closure that mutates aCopyvalue and expecting the outer variable to change. The closure mutates its own copy. - Adding
moveeverywhere "to be safe". It can cause unneeded clones or moves that block later use of the data.
Exercise
A closure uses let count = 0; let mut inc = move || { count_copy += 1; }; style logic on an i32 counter named count declared let mut count = 0;. After inc() is called twice, what does println!("{}", count) print, and why?
Show answer
It prints 0. i32 is Copy, so move gives the closure its own copy of count. The closure increments that copy, and the original variable is unchanged.