Why does Rust's `std::thread::spawn` require a `'static` closure, and how do you fix E0373 when it borrows a local vector?
answer
- the thread may outlive its caller
- the signature knows nothing about join
- F: Send + 'static
- move owned data in, or share it
basics
~20 sthread::spawn requires F: 'static because the new thread can outlive its caller, so a borrow of the caller's locals could dangle. Fix E0373 with move to hand owned data over, or move in an Arc clone to share it.
solid answer
~40 s`std::thread::spawn` is declared with `F: FnOnce() -> T + Send + 'static` and `T: Send + 'static`. The spawned thread has no parent-child tie to its caller: dropping the `JoinHandle` detaches it, so the compiler cannot assume the caller's stack frame is still there when the closure runs. A closure that borrows a local `Vec<u64>` is therefore rejected with E0373, `closure may outlive the current function, but it borrows samples, which is owned by the current function`. Adding `move` makes the closure own the vector, and an owned `Vec<u64>` is `'static`. If the caller still needs the data, move in an `Arc` clone instead. `move` does not help when the captured variable is itself a borrow, such as a `&[u64]` parameter: that fails with E0521.
code
rust · 10 linesuse std::thread;
fn main() {
let samples = vec![12_u64, 7, 31];
let reporter = thread::spawn(|| {
let total: u64 = samples.iter().sum();
println!("total latency {total} ms");
});
reporter.join().unwrap();
}go deeper
Recall that a closure passed to thread::spawn must not borrow local variables, and that adding move hands ownership to the thread.
Explain spawn's F: Send + 'static bound, why a detached thread can outlive its caller, and choose between move and moving an Arc clone.
Diagnose the cases move cannot fix, E0521 for a captured reference parameter and E0310 in a generic helper, and repair them by changing what the signature owns.
Set the team default for background work: owned or reference-counted data handed to threads, scoped threads where the borrow must stay, and no leaks added only to satisfy the bound.
## The signature that carries the rule `std::thread::spawn` in std 1.99.1 is declared as: ```rust pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static, ``` `Send` says the closure and its result may cross to another thread, which is the subject of Send and Sync. The **`'static` bound** is the lifetime half: the closure's type, which includes everything it captures, may contain no borrow shorter than `'static`. Owned captures pass; a captured `&Vec<u64>` pointing into the caller's stack does not. The bound is on the closure's **type**, so it is checked entirely at compile time; nothing at run time measures how long the thread actually lives. std's own doc comment explains why: threads can outlive the scope they were created in, and since the caller cannot know when the thread will finish, everything it uses must stay valid as long as the thread might run. The module docs add that there is no parent/child relationship between a spawning thread and the spawned one. ## Why joining right away does not convince the compiler Candidates often say "but I call `join()` on the next line". The borrow checker reasons from the signature, and `spawn`'s signature says nothing about joining. A `JoinHandle` can be dropped, which detaches the thread, or passed to `std::mem::forget`, which is safe code. Either way the thread keeps running after the caller returns, so the only sound rule for this API is to forbid short borrows outright. Scoped threads encode the join in their API and lift the bound; they belong with spawning and scopes. ## The metrics thread that fails A background reporter sums latency samples held in a local vector: ```plaintext error[E0373]: closure may outlive the current function, but it borrows `samples`, which is owned by the current function 5 | let reporter = thread::spawn(|| { | ^^ may outlive borrowed value `samples` note: function requires argument type to outlive `'static` help: to force the closure to take ownership of `samples` (and any other referenced variables), use the `move` keyword ``` Without `move`, the closure captures `samples` by reference because it only reads it, so its type contains a borrow of a local. ## The fixes, in order of preference 1. **Move the data in.** `thread::spawn(move || ...)` makes the closure own `samples`. A `Vec<u64>` has no lifetime parameters, so the closure is `'static`. The caller can no longer use `samples`. 2. **Share ownership.** Wrap the data in `std::sync::Arc`, clone the handle and move the clone in. `Arc<Vec<u64>>` is `'static`, the caller keeps its own handle, and the vector is freed when the last handle drops. Reference counting itself is covered with Mutex, RwLock and Arc. 3. **Send messages.** Give the thread a channel receiver and send owned values to it. 4. **Return results by value.** The closure's return value travels back through `join()`, which is why `T: 'static` is required too. 5. **Capture small copies.** If the thread needs only a threshold or a count, bind it to a local `u64` before spawning; with `move`, the closure gets its own copy, which holds no borrow. Avoid `std::rc::Rc` here: it is not `Send`, so rustc rejects it with E0277. ## When `move` is not enough `move` changes how variables are captured, not what they are. In ```rust fn spawn_report(samples: &[u64]) -> JoinHandle<u64> { thread::spawn(move || samples.iter().sum()) } ``` the closure now owns a copy of the reference, and that reference's lifetime is the caller's borrow. rustc 1.99 reports E0521, `borrowed data escapes outside of function`, with `argument requires that '1 must outlive 'static`. The fix is in the signature: take `Vec<u64>` or `Arc<[u64]>` by value. ## Generic helpers inherit the bound A wrapper such as `fn run_in_background<F: FnOnce() + Send>(job: F)` that calls `thread::spawn(job)` fails with E0310, `the parameter type F may not live long enough`, and rustc suggests adding `'static`. That suggestion is right here: the helper really does hand `job` to a thread of unknown lifetime. ## Summary of the bound's meaning | Captured value | Closure `'static`? | |---|---| | owned `Vec<u64>` moved in | yes | | `Arc<Vec<u64>>` clone moved in | yes | | `&'static str` literal | yes | | `&samples` borrowed from a local | no, E0373 | | a `&[u64]` parameter moved in | no, E0521 |
- If the caller always calls `join()` immediately, why is `'static` still required?The borrow checker only sees `spawn`'s signature, which promises nothing about joining. A `JoinHandle` can be dropped, detaching the thread, or forgotten with `std::mem::forget`, which is safe. Either way the thread can outlive the caller, so `spawn` must forbid borrows of the caller's locals. Scoped threads make the join part of the API instead.
- Why does adding `move` not fix a closure that captures a `&[u64]` parameter?`move` moves the variable, and the variable is a reference, so the closure owns a copy of a borrow whose lifetime belongs to the caller. That type is not `'static`, and rustc 1.99 reports E0521, `borrowed data escapes outside of function`. Take owned data, such as `Vec<u64>` or `Arc<[u64]>`, as the parameter.
- Why does a generic helper that forwards `F: FnOnce() + Send` to `thread::spawn` fail?Its bound is weaker than `spawn`'s, so `F` might capture short borrows. rustc 1.99 reports E0310, `the parameter type F may not live long enough`, and suggests `F: FnOnce() + Send + 'static`. Adding it is correct, because the helper genuinely passes `F` to a thread of unknown lifetime.
- Joining the handle on the next line lets the closure borrow the caller's locals.
- Adding move always fixes a 'static error from thread::spawn.
- The 'static bound means the spawned thread must run until the program exits.
- Wrapping the data in Rc and moving a clone in is the standard fix.
- Declaring the vector with let mut lets the closure borrow it across threads.