我正在使用具有两种类型的demo 3库:
PhysicalDevice
需要一个&Arc<Instance>
。我正在编写一个函数,该函数将包含Arc
的结构返回到这些类的实例,但是由于PhysicalDevice
需要&Arc<Instance>
的事实,借位检查程序未编译代码,即使实例超出了功能范围。
我对Pet
取&Arc<Person>
的问题进行了较小的复制。
在函数test
中,我创建了两个对象,并尝试以结构体返回它们:
use std::sync::Arc;
struct Person {
name: String,
}
struct Pet<'t> {
name: String,
owner: &'t Arc<Person>,
}
struct PersonPetPair<'a> {
person: Arc<Person>,
pet: Arc<Pet<'a>>,
}
fn test<'a>() -> PersonPetPair<'a> {
let person = Person {
name: String::from("ash"),
};
let person_arc = Arc::new(person);
let pet = Pet {
name: String::from("pikachu"),
owner: &person_arc,
};
let pet_arc = Arc::new(pet);
PersonPetPair {
person: person_arc,
pet: pet_arc,
}
// person_arc ends here, so the reference is invalid anymore
// Still, the objects are still alive since they are created with
// Arc<>
}
fn main() {
let t = test();
println!("{} owns {}", t.person.name, t.pet.name);
}
编译器告诉我有一个问题:
error[E0597]: `person_arc` does not live long enough
--> src/main.rs:25:17
|
25 | owner: &person_arc,
| ^^^^^^^^^^ borrowed value does not live long enough
...
36 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 17:9...
--> src/main.rs:17:9
|
17 | fn test<'a>() -> PersonPetPair<'a> {
| ^^
实际上,函数结束时将删除局部变量person_arc
。应该有一种避免此问题的方法,因为两个实例都由于使用了Arc
而无法使用该功能。