类型闭合不能满足所需的寿命

时间:2017-05-08 21:31:54

标签: rust

我有一个类似的代码:

use std::thread;

fn main() {
    let mut prefe: Prefe = Prefe::new();
    start(&prefe).join();
    println!("Test {}", prefe.cantidad);
}

fn start(pre: &Prefe) -> thread::JoinHandle<i32> {
    thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(50));
        let t: i32 = 3 as i32;
        t
    })
}

但是当试图使用它时:

std::thread::sleep(std::time::Duration::from_secs(pre.minutos_pom_corto));

我收到此错误:

error[E0477]: the type `[closure@src/main.rs:15:19: 22:6 pre:&Prefe]` does not fulfill the required lifetime
  --> src/main.rs:15:5
   |
15 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

在阅读了一些内容和Arc之后,我有了这个似乎有用的代码:

use std::thread;
use std::sync::Arc;

fn main() {
    let mut prefe: Prefe = Prefe::new();
    let test = Arc::new(prefe);
    start(test).join();    
    //println!("Test {}", prefe.cantidad); // <- With this commented
}

fn start(pre: Arc<Prefe>) -> thread::JoinHandle<i32> {
    thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(pre.minutos_pom_corto));
        let t: i32 = 3 as i32;
        t
    })
}

在不评论println!("Test {}", prefe.cantidad);的情况下,我收到此错误:

 let test = Arc::new(prefe);
    |                ----- value moved here

我尝试了以下内容:

//..
let test = Arc::new(&prefe);
//..

fn start(pre: Arc<&Prefe>) -> thread::JoinHandle<i32> {

但是我得到的错误类似于第一个错误

error[E0477]: the type `[closure@src/main.rs:19:19: 26:6 pre:std::sync::Arc<&Prefe>]` does not fulfill the required lifetime
  --> src/main.rs:19:5
   |
19 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

我尝试了以下更改,但仍然无效:

    //..
    let test = Arc::new(&prefe);
    start(&test).join();
    println!("{}", prefe.cantidad);
    //..

fn start(pre: &Arc<&Prefe>) -> thread::JoinHandle<i32> {
    //..
    let test = Arc::new(&prefe);
    let f = test.clone();
    start(&f).join();

    println!("{}", prefe.cantidad);
    //..

fn start(pre: &Arc<&Prefe>) -> thread::JoinHandle<i32> {

如何修复此错误,或者执行显示操作的正确方法是什么?

0 个答案:

没有答案