Rust: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement

Viewed 2688

I read the official Rust book, in particular the Fearless Concurrency chapter. I understand why this code does not compile. What I need is a some guidance how to fix it.

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);
    }
}

Produces a compile time error:

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

I am disallowed from importing crates, so this has to be done with std threads.

0 Answers
Related