I was running into this error when compiling code shown in the playground:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:30:32
|
30 | let token = self.token.clone();
| ^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined here...
--> src/main.rs:22:6
|
22 | impl<'a> MyServer<'a> {
| ^^
note: ...so that the types are compatible
--> src/main.rs:30:32
|
30 | let token = self.token.clone();
| ^^^^^
= note: expected `&TokenHolder<'_>`
found `&TokenHolder<'a>`
= note: but, the lifetime must be valid for the static lifetime...
I made the problem go away by changing:
impl<'a> MyServer<'a> {
to
impl<'a> MyServer<'static> {
One of my standard soapbox aphorisms is "There's a big difference between solving a problem and making a problem go away." I would like to understand why this made my error go away and therefore whether or not it is the correct way to solve my problem.
Here's my code (and my first time playing with the playground...)
--wpd
#![allow(dead_code)]
#[derive(Clone)]
struct TokenHolder<'a> {
i32_ref: &'a i32,
}
impl<'a> TokenHolder<'a> {
pub fn new() -> TokenHolder<'a> {
static TOKEN: i32 = 123;
TokenHolder { i32_ref: &TOKEN }
}
}
struct MyServer<'a> {
token: TokenHolder<'a>,
}
// This fails to compile
//impl<'a> MyServer<'a> {
// This works
impl<'a> MyServer<'static> {
pub fn new() -> MyServer<'a> {
MyServer { token: TokenHolder::new() }
}
pub fn run(&self) {
let token = self.token.clone();
some_function(move || home(&token));
}
}
fn main() {
let server = MyServer::new();
server.run();
}
fn home(_token: &TokenHolder) {}
fn some_function<F: 'static>(_: F){}
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 2.91s