Sub topic 3
Taking ownership with move
This chapter assumes you know ownership, borrowing and references, and the basic closure capture rules from the previous chapter. It covers what the move keyword changes, what it leaves alone, and the errors it prevents.
What move does
By default, a closure captures each variable in the least restrictive way its body needs: shared borrow, mutable borrow, or move. Putting move before the parameter list changes that. Every variable the closure uses is captured by value, whatever the body does with it.
- A non-
Copyvalue such as aStringorVecis moved into the closure. The original variable can no longer be used. - A
Copyvalue such as ani32is copied into the closure. The original stays usable, and the two copies are independent. - A reference such as
&Tis itself copied into the closure. The data behind it is not moved.
move affects only how variables get into the closure. It does not change what the closure body does.
The main use: closures that outlive their scope
The usual reason to write move is that the closure must live longer than the function that created it. thread::spawn is the standard case. The new thread may run after the spawning function returns, so it cannot borrow from that function's stack.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", data);
});
handle.join().unwrap();
}Without move, the closure would only need data by shared reference, so Rust would borrow it. The compiler then rejects the program with error E0373: the closure may outlive the current function, but it borrows data. The error message suggests adding move.
Move on Copy types copies the value
Because Copy types are copied, a move closure that mutates a captured integer changes only its own copy.
fn main() {
let mut count = 0;
let mut inc = move || {
count += 1;
println!("inside: {}", count);
};
inc();
inc();
println!("outside: {}", count);
}This prints inside: 1, inside: 2, then outside: 0. Without move, the closure would mutably borrow count and the last line would print 2. If you expected the outer variable to change and it didn't, check whether a move closure is working on a copy.
The closure still needs mut here. Calling it changes the captured state stored inside it.
Keeping a value you also need: clone first
When you move a non-Copy value into a closure, the original is gone. If you need both, make a copy before creating the closure and move the copy.
fn main() {
let name = String::from("Ada");
let name_for_closure = name.clone();
let greet = move || println!("Hello, {}", name_for_closure);
greet();
greet();
println!("{}", name);
}If you wrote move || println!("Hello, {}", name) and then used name afterwards, you would get error E0382, "borrow of moved value". The closure took ownership of name at the point where it was created, not where it was called.
Sharing across threads with Arc
Cloning a large Vec for every thread is wasteful. For read-only sharing, wrap the data in Arc (atomic reference counted pointer). Then clone the Arc, which copies only a pointer and increments a counter, and move each clone into its own closure.
use std::sync::Arc;
use std::thread;
fn main() {
let shared = Arc::new(vec![1, 2, 3]);
let mut handles = Vec::new();
for i in 0..3 {
let shared = Arc::clone(&shared);
handles.push(thread::spawn(move || {
let sum: i32 = shared.iter().sum();
i * sum
}));
}
let results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
println!("{:?}", results); // [0, 6, 12]
}The line let shared = Arc::clone(&shared); shadows the outer variable inside the loop body. Each iteration then moves its own handle into its own thread. The results are deterministic because join is called in order, even though the threads run in any order.
Move does not decide Fn, FnMut or FnOnce
A common misunderstanding is that a move closure can only be called once. That is false. The Fn traits depend on what the closure body does with captured values. move only decides how they were captured.
fn call_twice<F: Fn()>(f: F) {
f();
f();
}
fn run_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let msg = String::from("hi");
call_twice(move || println!("{}", msg));
let owned = String::from("done");
let result = run_once(move || owned);
println!("{}", result);
}The first closure owns msg but only reads it, so it implements Fn and can be called repeatedly. The second closure returns owned, which moves the value out of the closure. That makes it FnOnce only, and it could not be called a second time.
| Closure body | Capture without `move` | Capture with `move` | Traits implemented |
|---|---|---|---|
| Reads a `String` | Shared borrow | Owned | `Fn`, `FnMut`, `FnOnce` |
| Pushes to a `Vec` | Mutable borrow | Owned | `FnMut`, `FnOnce` |
| Returns the `String` | Owned (forced) | Owned | `FnOnce` |
Deciding whether you need move
Closures returned from functions are the other typical case. The returned closure cannot borrow from the function's locals, which are gone after the return, so it uses move. The returning-closures chapter covers this in full.
Edge cases
Moving a reference moves only the reference
A move closure that captures a reference copies the reference, not the data.
fn main() {
let text = String::from("borrowed");
let r = &text;
let show = move || println!("{}", r);
show();
println!("{}", text);
}This compiles because text was never moved. The closure still holds a borrow of text, so it cannot outlive text. Adding move does not remove lifetime limits when you capture references.
Only the variables you use are captured
In the 2021 edition and later, closures capture individual fields rather than whole structs when the body uses only some fields. A move closure moves just those fields, so you can often keep using the other fields of the struct afterwards. Older editions captured the whole variable. If code that compiles in one edition fails in another, check this first.
Dropping happens when the closure drops
Moved values are dropped when the closure is dropped, not when the original variable's scope ends. A File or MutexGuard moved into a long-lived closure stays open or locked for as long as the closure exists.
Common errors
- E0373, closure may outlive the current function: add
move, or restructure so nothing borrowed crosses the thread boundary. - E0382, use of moved value: you used a variable after a
moveclosure took it. Clone it first, share it withArc, or stop using the original. - E0525, expected a closure that implements
Fn, but it only implementsFnOnce: the body moves a captured value out. Clone the value inside the body, or change the bound toFnOnce. Rccannot be sent between threads safely:Rcis notSend. UseArcwhen amoveclosure goes tothread::spawn.
Exercise
The code below compiles and prints two lines. What does it print, and why does the second line differ from what it would print if move were removed?
fn main() {
let mut total = 10;
let mut add = move |n: i32| {
total += n;
total
};
println!("{}", add(5));
println!("{}", total);
}
Show answer
It prints 15, then 10. total is an i32, which is Copy, so move gives the closure its own copy. Adding 5 changes only the closure's copy, so the outer total stays 10. Without move, the closure would mutably borrow total. Printing total while add was still in scope could then conflict with that borrow, and after the closure's last use the outer total would be 15.