I currently want to define a struct for a Piston game using GamerIterator:
pub struct MyGame<'a> {
game_window: GameWindowGLFW,
game_iter: GameIterator<'a, GameWindowGLFW>,
//...
}
The GameIterator
is generic in the GameWindow
and its lifetime. I want to tell the compiler that it has the same lifetime as the field "game_window"/"the whole struct" and leave out the lifetime for the struct.
I also have difficulties initializing this:
MyGame {
game_window: GameWindowGLFW::new(GameWindowSettings {/*...*/},
game_iter: GameIterator::new(&mut game_window, &game_iter_settings), // game_window cannot be used here
//...
}
I think that I can work around the initialization issue by using Option<GameIterator<...>>
and an init() method, but I would like to avoid this because I can guarantee that game_iter
is present after new()
finishes.
What is the idiomatic way to write this?
Not only is there an issue with initialization, there could also be issues with destruction, if
GameIterator
implementedDrop
: the compiler would have to know that it needs to destructgame_iter
beforegame_window
, otherwisegame_window
would have a reference to a destroyedGameWindowGLFW
while running itsdrop()
method.There's no way to pass the lifetime of the struct itself as a lifetime argument. The only thing you can do is remove the
game_window
field fromMyGame
and pass aGameWindowGLFW
instance toMyGame
's initializer. If you want to encapsulate this so that the user doesn't need to create aGameWindowGLFW
, you could write a method that creates aGameWindowGLFW
and aMyGame
on the stack and calls a closure that accepts aMyGame
argument only.