I'm working on a hobby game engine, and I have a struct Mesh
and a view over it with Instance
:
struct Mesh {
// Vertex info, etc
}
struct Instance<'a> {
mesh: &'a Mesh,
transform: Mat4,
}
This seems to me to be exactly what the lifetime rules are for; I'm declaring that the Instance
has to live a shorter life than the Mesh
it's holding a reference to.
When I try to use this in my main function:
fn main() {
let mesh = Mesh::new();
// Add vertices, etc
// Scene has a Vec<Box<dyn Drawable>>, which Instance implements.
let mut scene = Scene::new(glam::Mat4::zero());
scene.push(Box::new(Instance::new(&mesh, glam::Mat4::zero())));
render_scene(scene)
}
I get the following error from the borrow checker:
error[E0597]: `mesh` does not live long enough
--> bin/rendertest.rs:9:39
|
9 | scene.push(Box::new(Instance::new(&mesh, glam::Mat4::zero())));
| -----------------------^^^^^----------------------
| | |
| | borrowed value does not live long enough
| cast requires that `mesh` is borrowed for `'static`
...
12 | }
| - `mesh` dropped here while still borrowed
What is the cast it's talking about? And why does it need the mesh to be 'static
? It seems like the mesh should live past the return of render_scene, when main
exits.