These simple code can not compile.
trait A {}
struct B;
impl A for B {}
struct C {
a: Box<dyn A>
}
impl C {
fn f(&self) -> i32 {
1
}
}
let b: Box<dyn A> = Box::new(B);
let c = C { a: b };
thread::scope(|scope| {
scope.spawn(|| c.f());
scope.spawn(|| c.f());
})
[E0277] Error: `(dyn A + 'static)` cannot be shared between threads safely
╭─[command_257:1:1]
│
2 │ scope.spawn(|| c.f());
· ──┬── ─┬──┬───
· ╰───────────── required by a bound introduced by this call
· │ │
· ╰──────── note: required because it's used within this closure
· │
· ╰───── `(dyn A + 'static)` cannot be shared between threads safely
·
· Note: note: required because it appears within the type `Box<(dyn A + 'static)>`note: required because it appears within the type `C`
───╯
I thought c
is just immutable shared between threads, it won't be changed by any thread. I can not figure out why it says "unsafe". What should I do?