博客文章系列Understanding Lifetime in Rust以悬崖形式结尾,总结如下......
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);
}
果然,在编译时,car
的活动时间不够长。
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 | | }
| |_^
该帖子声称在第三部分中解决了这个问题......
这是因为只要购买它的人,汽车对象就不会存在。那么我们如何才能继续引用在内部作用域中创建的对象呢?答案在于堆分配,在Rust中通过Box :: new实现。我们将在第三部分进行探讨。
......但没有第三部分。
我正试图解决一个非常类似的问题,让第三部分有所帮助。
你能回答第三部分吗?
答案 0 :(得分:1)
答案在于堆分配,在Rust中通过
Box::new
实现。
不需要通过Box
进行堆分配;只需拥有Car
:
struct Car {
model: String,
}
struct Person {
car: Option<Car>,
}
impl Person {
fn new() -> Person {
Person { car: None }
}
fn buy_car(&mut self, c: Car) {
self.car = Some(c);
}
fn sell_car(&mut self) {
self.car = None;
}
fn trade_with(&mut self, other: &mut Person) {
std::mem::swap(&mut self.car, &mut other.car);
}
}
fn shop_for_car(p: &mut Person) {
let car = Car {
model: "Mercedes GLK350".to_string(),
};
p.buy_car(car);
}
fn main() {
let mut p = Person::new();
shop_for_car(&mut p);
}
fn main() {
let mut p = Person::new();
shop_for_car(&mut p);
}
如果您想在堆上虚假地分配内存,欢迎您更改为Box<Car>
。
另见: