SDL2 lifetime question

I did not do the legwork to understand SDL2.

But if I understand your code correctly, you had a situation like so:

// The fields don't matter for this illustration, just the lifetimes involved
struct Font<'a>(&'a str);
struct Context;

impl Context {
    // Creation of a font borrows the context
    fn load_font(&self) -> Font<'_> {
        Font("dummy")
    }
}

And you wanted to store them together:

struct StoreTogether<'a> {
    ctx: Context,
    // Borrowed from the `ctx` field
    font: Font<'a>,
}

That would be a self-referential struct, which is an anti-pattern in Rust. You can't actually created it without borrowing StoreTogether<'a> for 'a, which makes it mostly unusable (if it can compile at all).


Rust lifetimes (those '_ things) don't describe the length of a value's liveness, such as how long StoreTogether<'_> exists before destructed. When you create a sdl2::ttf::Font<'ttf, '_>, 'ttf represents the length of the borrow of the sdl2::ttf::Sdl2TtfContext. It doesn't represent the Sdl2TtfContext still being alive.

(Lifetimes are a compile-type analysis and don't exist at runtime at all.)

1 Like