gpt4 book ai didi

rust - 使用 "heap allocation"修复对生命周期不够长的引用的包含

转载 作者:行者123 更新时间:2023-11-29 08:18:35 32 4
gpt4 key购买 nike

博文系列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 | | }
| |_^

帖子结束时声称要在第三部分解决这个问题......

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.

...但是没有第三部分。

我正在尝试解决一个非常相似的问题,拥有第 III 部分会有所帮助。

你能回答第三部分吗?

最佳答案

The answer lies in heap allocation which in Rust is achieved via 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> 来实现。 .

另见:

关于rust - 使用 "heap allocation"修复对生命周期不够长的引用的包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47824987/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com