Thread and static


I am getting this error:

error[E0373]: closure may outlive the current function, but it borrows `o`, which is owned by the current function
 --> src/
5 |     builder.spawn(|| o);
  |                   ^^ - `o` is borrowed here
  |                   |
  |                   may outlive borrowed value `o`
help: to force the closure to take ownership of `o` (and any other referenced variables), use the `move` keyword, as shown:
  |     builder.spawn(move || o);


use std::thread;

fn foo(o: &'static i32) {
    let builder = thread::Builder::new();
    builder.spawn(|| o);

static i: i32 = 30;

fn main() {

Why is it saying that o is owned by foo, when it’s static?


I should add that the actual code is more complicated and hence I cannot use &i directly in foo


Yeah, I think this is an artifact of how closures capture their environment. What you’re ending up with here is roughly:

struct Closure<'a> {
    o_capture: &'a &'static i32

The compiler deduced that a reference to the captured value suffices and you end up with a reference to a reference.

If you add the move like the compiler suggests, it’ll create what you’re looking for:

struct Closure {
    o_capture: &'static i32