将闭包(returns 具有特征的结构)发送到线程会导致大小错误

Sending a closure (which returns a struct with a trait) to a thread leads to sized error

我正在尝试发送一个将生成结构的闭包给线程,但是当我尝试这样做时,我收到了 Sized 错误。我理解这个错误(在编译时确实不知道大小),但是添加 Boxes 和其他类似的技巧似乎并没有解决它。

我试图研究如何实现 Sized 特性,但它似乎很特别,老实说超出了我的理解范围。

我写了一个最小的可重现示例:

use std::thread;

trait DataProcess {
    fn start(&self);
    fn run(&self);
    fn stop(&self);
}

struct SomeDP {
    name: String,
}

impl DataProcess for SomeDP {
    fn start(&self) {
        println!("Started");
    }
    fn run(&self) {
        println!("Running");
    }
    fn stop(&self) {
        println!("Stopped");
    }
}

fn thread_maker(builder: Box<dyn Fn() -> (dyn DataProcess + Send)>) {
    let thread_builder = thread::Builder::new();
    let handle = thread_builder.spawn(move || {
        let dp = builder();
        dp.start();
    });
}

fn main() {
    let dp_builder = || SomeDP {
        name: "nice".to_string(),
    };
    thread_maker(Box::new(dp_builder));
}

你也可以在操场上找到here

这个有效

use std::thread;

trait DataProcess{
    fn start(&self);
    fn run(&self);
    fn stop(&self);
}

struct SomeDP{
    name: String
}

impl DataProcess for SomeDP{
    fn start(&self){println!("Started");}
    fn run(&self){println!("Running");}
    fn stop(&self){println!("Stopped");}
}

fn thread_maker<F>(builder: F)
where
    F: Fn() -> Box<dyn DataProcess>,
    F: Send + 'static {
    let thread_builder = thread::Builder::new();
    let handle = thread_builder.spawn(
        move ||{
            let dp = builder();
            dp.start();
        }
    );
}

fn main(){
    let dp_builder = || -> Box<dyn DataProcess> {
        Box::new(SomeDP{name: "nice".to_string()})
    };
    thread_maker(dp_builder);
}