So I'm building a game engine in rust, but I have an issue with finding the correct lifetime parameters/syntax for storing the font data the sdl2 library needs for rendering.
This is a simplified version of what I'm currently doing, but it doesn't compile. As far as I can tell, the first lifetime parameter of the Font
object given by ttf.load_font()
must match the lifetime of the ttf
object itself, but I can't come up with the correct syntax or data structures to tell the compiler about that lifetime relationship.
My current understanding is that ttf
has the same (or shorter) lifetime as FontManager
, being a data member, and any Font
object created will have a lifetime tied to the ttf
object that created it. So the <'a>
in FontManager should be the same lifetime. There's obviously something I'm missing here, since it doesn't quite work, but I'm not sure what it is. If anyone could help explain what's going on, I would be immensely grateful.
mod sdl2;
struct FontManager<'a> {
pub ttf: sdl2::ttf::Sdl2TtfContext,
pub font: Option<sdl2::ttf::Font<'a, 'static>>,
}
impl<'a> FontManager<'a> {
pub fn load_font(&'a mut self, path: &std::path::Path, size: usize) {
match self.ttf.load_font(&self.ttf, path, size as u16) {
Err(e) => panic!("{:?}", e),
Ok(font) => { self.font = Some(font); }
}
}
}
fn main() -> Result<(), String> {
let ttf = sdl2::ttf::init().map_err(|e| e.to_string())?;
let mut fm = FontManager { ttf, font: None };
fm.load_font(std::path::Path::new("Arial.ttf", 16); // <- error: 'fm' does not live long enough
// ...main game loop...
} // <- error: 'fm' dropped here while still borrowed