Rust:`self` 有一个匿名生命周期 `'_`,但它需要满足一个 `'static` 生命周期要求

问题描述

我阅读了 Rust 的官方书籍,尤其是 Fearless Concurrency 一章。我明白为什么这段代码不能编译。我需要的是一些如何修复它的指导。

impl Maze {
    fn solve (&self,points: String) -> Path {
        ...

        use std::thread::{spawn,JoinHandle};
        use std::sync::mpsc::channel;
        use std::sync::Arc;

        let mut mazearc = Arc::<&Maze>::new(&self);

        let mut threads = Vec::<JoinHandle<_>>::with_capacity(128);
        let (tx,rx) = channel();

        for i in 0..path.len() {
            let txcopy = tx.clone();
            let segcopy = path[i].clone();
            let sharedmaze = mazearc.clone();
            threads.push(spawn(move || {
                let partialpath = sharedmaze.solve_segment(segcopy);
                txcopy.send((i,partialpath));
            }));
        }

        for h in threads.into_iter() {
            h.join();
        }

        let mut pp: Vec::<(usize,Vec::<Point>)> = rx.iter().collect();
        pp.sort_by_key(|s| s.0);

        for i in 0..path.len() {
            path[i].nodes = pp[i].1.clone();
        }

        return Path::join(path,&self);
    }
}

产生编译时错误

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
   --> temp.rs:228:21
    |
200 |     fn solve (&self,points: String) -> Path {
    |               ----- this data with an anonymous lifetime `'_`...
...
228 |         let mut mazearc = Arc::<&Maze>::new(&self);
    |                           ^^^^^^^^^^^^^^^^^ ----- ...is captured here...
...
237 |             threads.push(spawn(move || {
    |                          ----- ...and is required to live as long as `'static` here

我被禁止导入 crate,所以这必须使用 std 线程来完成。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)