克隆和移动特征

Cloning and moving traits

我希望能够将实现特征 Foo 的对象的克隆版本移动到各种线程中。我似乎无法弄清楚这是如何实现的。我试过克隆和移动 Box<Foo> 并将参数指定为通用参数,但似乎无法让编译器满意。

我的第一次尝试:

use std::thread;

pub trait Foo {
    fn bar();
}

pub struct Thing;

impl Thing {
    pub fn something(handler: Box<Foo>) {
        let handler_1 = handler.clone();
        thread::spawn(move || {
            Thing::another_thread(handler_1)
        });
    }

    fn another_thread(handler: Box<Foo>) { }
}

导致以下错误:

error: no method named clone found for type Box<Foo + 'static> in the current scope
error: the trait core::marker::Send is not implemented for the type Foo [E0277]

接下来我试着把它写成一个泛型参数...

use std::thread;

pub trait Foo {
    fn bar();
}

pub struct Thing;

impl Thing {
    pub fn something<T: Foo + Clone + Send>(handler: T) {
        let handler_1 = handler.clone();
        thread::spawn(move || {
            Thing::another_thread(handler_1)
        });
    }

    fn another_thread<T: Foo>(handler: T) { }
}

收到以下错误:

error: the parameter type T may not live long enough [E0310]
help: consider adding an explicit lifetime bound T: 'static...

现在我们已经到了迷路的地步,我开始 <'a> 戳每个缝隙,希望它能解决问题。但是,不幸的是,我不知道我想要实现的目标的语法是什么。在此先感谢您的帮助!

consider adding an explicit lifetime bound T: 'static...

看起来像这样:

pub fn something<T: 'static + Foo + Clone + Send>(handler: T)

编译。

如果您不熟悉此语法,这意味着无论选择 T 的具体类型,它都必须超过 'static 生命周期。这包括具体类型可能具有的任何内部引用/生命周期。