I'm new to Rust, and I'm trying to learn more about lifetimes. I came across the following piece of code, which won't compile (Playground):
struct Person<'a, 'b> {
name: &'a str,
email: &'b str,
}
fn main() {
let my_name: String = String::from("John Doe");
let me: Person;
{
let my_email: String = String::from("[email protected]");
me = Person {
name: &my_name,
email: &my_email,
};
}
println!("My name is {}.", me.name);
}
Notice the use of two different lifetime parameters in the definition of Person
.
Here is the compilation error:
error[E0597]: `my_email` does not live long enough
--> src/main.rs:15:20
|
15 | email: &my_email,
| ^^^^^^^^^ borrowed value does not live long enough
16 | };
17 | }
| - `my_email` dropped here while still borrowed
18 |
19 | println!("My name is {}.", me.name);
| ------- borrow later used here
The compiler complains about my_email
not living long enough. However, I'm not using it, or any reference to it (me.email
, for example). I'm rather trying to print me.name
, which refers to my_name
, and the lifetime of it won't end until the end of main
function.
However, the following piece of code, which is a small modification of the code above, compiles and runs as intended (Playground):
struct Person<'a, 'b> {
name: &'a str,
email: &'b str,
}
fn main() {
let my_name: String = String::from("John Doe");
let name_ref: &str;
let me: Person;
{
let my_email: String = String::from("[email protected]");
me = Person {
name: &my_name,
email: &my_email,
};
name_ref = me.name;
}
println!("My name is {}.", name_ref); // Prints "My name is John Doe."
}
I can't understand why the first piece of code doesn't work, despite everything looking fine. Can someone explain what's going on?