This is my first ever rust program... building a snake game.
Everything was going fantastically, until I tried to add text... I have spent 3.5 hours now trying to debug this lifetime and ... it is going soul crushingly bad.
I did find this, but I couldn't really deduce the solution: Font and Lifetime · Issue #605 · Rust-SDL2/rust-sdl2 · GitHub
I don't think I need to put all my code, but the relevant part is here...
Based on my understanding, it seems Font can outlive Context... but why can I not define these together? I don't want to define the ttf context in main as I was trying to keep it compartmentalized.
pub struct TextContext {
ttf_context: sdl2::ttf::Sdl2TtfContext,
pub font: sdl2::ttf::Font<'static, 'static>,
}
impl TextContext {
pub fn new(path: &str, size: u16) -> Self {
let ttf_context = sdl2::ttf::init().unwrap();
let font = ttf_context.load_font(path, size).unwrap();
Self { ttf_context, font }
}
}
pub fn load_font<'ttf, P>(&'ttf self, path: P, point_size: u16) -> Result<Font<'ttf, 'static>, String>
where
P: AsRef<Path>,
...
pub struct Font<'ttf_module, 'rwops> {
raw: *mut ttf::TTF_Font,
// RWops is only stored here because it must not outlive
// the Font struct, and this RWops should not be used by
// anything else
// None means that the RWops is handled by SDL itself,
// and Some(rwops) means that the RWops is handled by the Rust
// side
#[allow(dead_code)]
rwops: Option<RWops<'rwops>>,
#[allow(dead_code)]
_marker: PhantomData<&'ttf_module ()>,
}
Here are the errors:
H src/window.rs 42:13 binding `ttf_context` declared here
H src/window.rs 43:20 argument requires that `ttf_context` is borrowed for `'static`
E src/window.rs 43:20 `ttf_context` does not live long enough
H src/window.rs 43:20 borrow of `ttf_context` occurs here
E src/window.rs 44:16 cannot move out of `ttf_context` because it is borrowed
H src/window.rs 45:5 `ttf_context` dropped here while still borrowed
In my main.rs it looks like this:
let mut window = Window::new(WIDTH * SCALE, HEIGHT * SCALE);
let text_context = TextContext::new("src/fonts/daydream.ttf", 18);
...
let text = format!("Score: {}", &game.score);
draw_text(&mut window, &text, &text_context, 10, 10);
...
// inside draw_text()
let surface = text_context.font.render(text).blended(GREEN).unwrap();