Hello!
I'm new to rust and need your help with the following code. If I just comment out the line 33, it will compile. I don't see the real difference between declaration of a and b variables (lines 26 and 27 respectively). But lifetimes of this variables are different. Why? How is it possible to extend the lifetime of b to fix the problem?
Many thanks in advance!
use std::thread;
trait Trait: Send + Sync + 'static {
fn foo(&self);
}
struct A;
impl Trait for A {
fn foo(&self) {
println!("I'm the struct A");
}
}
struct B {
name: String,
}
impl Trait for B {
fn foo(&self) {
println!("I'm the struct B. My name is {}.", self.name);
}
}
fn main() {
let a = &A {};
let b = &B {
name: "Bob".to_string(),
};
let mut vec: Vec<&dyn Trait> = Vec::new();
vec.push(a);
vec.push(b);
let handler = thread::spawn(|| {
for it in vec {
it.foo();
}
});
handler.join().unwrap();
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:27:14
|
27 | let b = &B {
| ______________^
28 | | name: "Bob".to_string(),
29 | | };
| |_____^ creates a temporary which is freed while still in use
...
33 | vec.push(b);
| - cast requires that borrow lasts for `'static`
...
42 | }
| - temporary value is freed at the end of this statement
error: aborting due to previous error
For more information about this error, try `rustc --explain E0716`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.