0

The exact error from my minimal reproducible example:

cannot infer an appropriate lifetime due to conflicting requirements

note: ...so that the types are compatible:
      expected &test_struct
         found &test_struct
note: but, the lifetime must be valid for the static lifetime...rustc(E0495)

I get this error in a much larger project as I was trying to thread calls to a function of a struct.

Here's the code that is a minimal reproducible example, producing the same error:

use std::thread;

pub struct test_struct {}

impl test_struct {
    fn inner_test_fn(&self) -> u32 {
        return 4u32;
    }
    pub fn outer_test_fn(&self) -> u32 {
        let mut threads = vec![];
        let mut total = 0u32;
        for i in 0..4 {
            threads.push(thread::spawn(move || {
                let out = self.inner_test_fn();
                total += out;
            }));
        }
        for thread in threads {
            thread.join();
        }
        return total;
    }
}

fn main() {
    let struct_holder = test_struct{};
    let x = struct_holder.outer_test_fn();
}

I am almost certain the error is because of self.inner_test_fn(); but after this point I'm at a loss.

I have and am looking up and reading more about lifetimes right now, but I can't quite figure this out yet.

I am aware of other questions around the same error, but both questions and answers to these are far more complex and difficult to understand than my simple example.

Any help would be greatly appreciated.

Jonathan Woollett-light
  • 2,813
  • 5
  • 30
  • 58
  • @Stargateur Both the answer and question you have linked are beyond my understanding. Although it could be the same fundamental issue, I think my far simpler question is relatively simple for someone to answer, and a far better resource to understand the issue than what you have linked. – Jonathan Woollett-light Dec 25 '19 at 13:27
  • While the other question is a bit more complex than yours, the answer would be pretty much identical: the `std` threads can outlive local variables, that's not safe. Different crates provide alternatives as shown in the other answer. You also have an issue because of `total`, which needs to be atomic to work with threads. – mcarton Dec 25 '19 at 13:38
  • 1
    [The duplicate applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=adc522a1d0d06c8171f6c3650921f2d2) – mcarton Dec 25 '19 at 13:44
  • @JonathanWoollett-light trust me I think the answer in the duplicate is WAY more simple that an answer to explain you why rust produce this particular error message. And in the end the answer is use something like scope if you want to this with your thread or clone everything like &self. – Stargateur Dec 25 '19 at 14:08
  • [Another example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=929b18a00ed3b67bba61edfc4716e878) – Stargateur Dec 25 '19 at 14:22

0 Answers0