我想在任务之间发送一个特征对象,但无法弄清楚它是否可能.它似乎可能不是,因为它们显然不符合这一Send特性.
以下代码演示了我正在尝试做的事情:
use std::{
sync::mpsc::{channel, Receiver, Sender},
thread,
};
trait Bar {
fn bar(&self);
}
struct Foo {
foo: i32,
}
impl Bar for Foo {
fn bar(&self) {
println!("foo: {}", self.foo);
}
}
fn main() {
let foo = Box::new(Foo { foo: 1 }) as Box<dyn Bar>;
let (tx, rx): (Sender<Box<dyn Bar>>, Receiver<Box<dyn Bar>>) = channel();
thread::spawn(move || {
tx.send(foo).unwrap();
});
let sent = rx.recv().unwrap();
sent.bar();
}
Run Code Online (Sandbox Code Playgroud)
此操作失败,并显示以下消息:
error[E0277]: `dyn Bar` cannot be sent between threads safely …Run Code Online (Sandbox Code Playgroud)