The blog post series Understanding Lifetime in Rust ends with a cliffhanger summarized as follows...
struct Car {
model: String,
}
struct Person<'a> {
car: Option<&'a Car>,
}
impl<'a> Person<'a> {
fn new() -> Person<'a> {
Person { car: None }
}
fn buy_car(&mut self, c: &'a Car) {
self.car = Some(c);
}
fn sell_car(&mut self) {
self.car = None;
}
fn trade_with(&mut self, other: &mut Person<'a>) {
let tmp = other.car;
other.car = self.car;
self.car = tmp;
}
}
fn shop_for_car(p: &mut Person) {
let car = Car {
model: "Mercedes GLK350".to_string(),
};
p.buy_car(&car); //Error! car doesn't live long enough
}
fn main() {
let mut p = Person::new();
shop_for_car(&mut p);
}
Sure enough, when compiled, car
does not live long enough.
error[E0597]: `car` does not live long enough
--> src/main.rs:35:16
|
35 | p.buy_car(&car); //Error! car doesn't live long enough
| ^^^ does not live long enough
36 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #2 defined on the function body at 30:1...
--> src/main.rs:30:1
|
30 | / fn shop_for_car(p: &mut Person) {
31 | | let car = Car {
32 | | model: "Mercedes GLK350".to_string(),
33 | | };
34 | |
35 | | p.buy_car(&car); //Error! car doesn't live long enough
36 | | }
| |_^
The post ends claiming to solve this in Part III...
That is because the car object simply doesn’t live as long as the Person buying it. So how can we keep reference to an object that is created in an inner scope like a function? The answer lies in heap allocation which in Rust is achieved via Box::new. We will explore that in Part III.
...but there is no Part III.
I'm trying to solve a very similar problem and having Part III would help.
Can you answer with Part III?