1 This error occurs when an attempt is made to use data captured by a closure,
2 when that data may no longer exist. It's most commonly seen when attempting to
6 fn foo() -> Box<Fn(u32) -> u32> {
12 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
13 closed-over data by reference. This means that once `foo()` returns, `x` no
14 longer exists. An attempt to access `x` within the closure would thus be
17 Another situation where this might be encountered is when spawning threads:
24 let thr = std::thread::spawn(|| {
30 Since our new thread runs in parallel, the stack frame containing `x` and `y`
31 may well have disappeared by the time we try to use them. Even if we call
32 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
33 stack frame won't disappear), we will not succeed: the compiler cannot prove
34 that this behaviour is safe, and so won't let us do it.
36 The solution to this problem is usually to switch to using a `move` closure.
37 This approach moves (or copies, where possible) data into the closure, rather
38 than taking references to it. For example:
41 fn foo() -> Box<Fn(u32) -> u32> {
43 Box::new(move |y| x + y)
47 Now that the closure has its own copy of the data, there's no need to worry