The following codes show two closures: c1, c2. c1 is returned by a function, c2 is generated locally. c1 can not be sent to a thread. Why?
fn gen_closure() -> Box<dyn Fn(&str)> {
return Box::new(|s: &str| {
println!("gen_closure: {}", s);
});
}
fn main() {
let c1 = gen_closure();
let c2 = Box::new(|s: &str| {
println!("main_closure: {}", s);
});
/* `dyn for<'r> Fn(&'r str)` cannot be sent between threads safely
the trait `Send` is not implemented for `dyn for<'r> Fn(&'r str)`
required because of the requirements on the impl of `Send` for `Unique<dyn for<'r> Fn(&'r str)>`
required because it appears within the type `[closure@src/main.rs:13:24: 15:6]` */
std::thread::spawn(move || {
(c1)("c1");
});
/* This is okay */
std::thread::spawn(move || {
(c2)("c2");
});
}