Sending trait objects between threads

I tried to send a trait object like the following:

trait Foo
{
    fn foo(&self);
}

struct Baz 
{
    pub data : Box<Foo>
}

fn Bar(baz : Baz) {
    thread::spawn(move || {baz.data.foo()});
}

Which gave me this error

'error: the trait `core::marker::Send` is not implemented for the type `TFoo` [E0277]

This is not surprising because (and please correct me if I'm wrong), the compiler does not know if the actual underlying object of the trait object Foo is Send or not. So the question is, is there a way to send a trait object between threads?

1 Like
pub data : Box<Foo + Send>
1 Like

You can require trait objects implement Send or Sync via + Send or + Sync. In this case, pub data: Box<Foo + Send>.

This is sadly a pervasive decision: everywhere you expect a trait object you need to choose if you require it to be Send or Sync upfront, and once it's been trait-ified you can't upgrade to + Send.

use std::thread;

trait Foo {
    fn foo(&self);
}

struct Baz {
    pub data : Box<Foo + Send>
}

fn Bar(baz : Baz) {
    thread::spawn(move || {baz.data.foo()});
}

fn main() {}
3 Likes