Lifetime conflicting requirements with simple integers and threads

Hi guys,

I guess the answer to this behaviour is extremely simple but I can't figure it out :persevere:

Here my code:

use std::thread;

fn main() {
    let test = TestThread{
        value: 0
    };
    test.start();
}

struct TestThread {
    value: i32
}

impl TestThread {
    fn start(&self) {
        let value = self.value;
        thread::spawn(move || {
            start_one(0);           // this is ok
            start_one(value);       // this is ok
            start_one(self.value);  // this is not ok, why?!
        });
    }
}

pub fn start_one(value: i32) {}

The code does not compile with this error caused by the "start_one(self.value)" call:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements

I thought that "start_one(self.value)" would pass a copy of the integer value, so what is causing the lifetime issue?!?
I am especially baffled by the fact that the previous line (i.e. start_one(value); ) works at it seems to me that the two calls are technically identical.

1 Like

You're definitely right that this function call would pass a copy of the integer value to the start_one. But that's not the layer that Rust is complaining about. Closure has something like an "environment" that contains every local variable, that the function uses – in this case it's value and self. You can imagine it as:

struct MyClosuresEnvironment<'a> {
    self: &'a TestThread,
    value: i32,
}

So it's putting self into the closure struct what Rust is complaining about.

3 Likes

@krdln

wow! So clear now!
Thank you very much, I was going mad with it. I was sure the answer was simple but I couldn't find it by myself.
:clap:

1 Like