I am using the vulkano library that has the two types:
PhysicalDevice
takes an &Arc<Instance>
. I am writing a function that returns a struct containing an Arc
to instances to these classes, but, due to the fact that PhysicalDevice::enumerate
requires an &Arc<Instance>
, the borrow checker is not compiling the code, even if the instances live beyond the function.
I've created a smaller reproduction of the problem where Pet
takes a &Arc<Person>
.
In the function test
, I create both objects and try to return them in a struct:
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);
}
The compiler tells me there is a problem:
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> {
| ^^
Indeed, the local variable person_arc
is being dropped when the function ends. There should be a way to avoid this problem since both instances outlive the function thanks to the use of Arc
.