“the type does not fulfill the required lifetime” when using a method in a thread

前端 未结 1 1336
礼貌的吻别
礼貌的吻别 2021-01-18 19:01

I am trying to use a method in a thread in Rust, but I get the following error message

:21:10: 21:23 error: the type [closure@:21:2

相关标签:
1条回答
  • 2021-01-18 19:28

    The problem is that every variable moved to the thread must have the lifetime 'static. i.e. threads can't reference values which are not owned by the thread.

    In this case the problem is that self is a reference to an instance of MyStruct.

    To solve it, remove every reference and clone the structure before sending it to the thread.

    use std::thread;
    use std::sync::mpsc;
    
    #[derive(Clone)]
    struct MyStruct {
        field: i32
    }
    
    impl MyStruct {
        fn my_fn(&self, adder1: i32, adder2: i32) -> i32 {
            self.field + adder1 + adder2
        }
    
        fn threade_test(&self) {
            let (tx, rx) = mpsc::channel();
            let adder = 1;
            let lst_adder = vec!(2, 2, 2);
    
            for a in lst_adder {
                let tx = tx.clone();
    
                let self_clone = self.clone();
                thread::spawn(move || {
                    let _ = tx.send(self_clone.my_fn(adder, a));
                });
            }
    
            println!("{}", rx.recv().unwrap());
        }
    }
    
    fn main() {
        let ms = MyStruct{field: 42};
        ms.threade_test();
    }
    
    0 讨论(0)
提交回复
热议问题