In the process of an entity-component system, I'm having this issue where I want all my objects in my scene to be able to use methods on the scene as mutable. However, I don't think keeping a reference to the scene is a good idea, as the scene is the structure containing the objects (so it would make a cycling reference), and I can't have multiple mutables references.
The idea that i got is that my objects have a function that borrows the scene : each time I want to do something on the scene from my object, I borrow the scene and then drop the borrow.
This is what I tried so far :
This is my Scene structure
pub struct GameScene {
// array of all objects
objects: Vec<GearObject>,
components: ComponentTable,
}
And there is my object :
pub struct GearObject<'o, 's:'o> {
transform: Transform,
id: u32,
get_scene: &'o dyn Fn() -> &'s mut GameScene,
}
impl<'s:'o, 'o> GearObject<'o, 's> {
pub fn empty(id: u32, scene_borrow: &'s mut GameScene) -> GearObject<'o, 's> {
// creates an empty gearObject
return GearObject {
id: id,
transform: Transform::origin(),
get_scene: &|| scene_borrow,
};
}
}
The idea was that my 'get_scene' would be a function that could borrow the scene
However, I'm not sure if I'm doing this correctly, the code doesn't even compile ("cannot infer an appropriate lifetime for lifetime parameter 's
due to conflicting requirements")
Does this keeps a reference to my scene, or is it doing what I was expecting, only borrowing the scene when called? Also, Why do I have a lifetime issue here ? am I not guaranting that my scene lives longer than my function to get it ?