I'm reading the code of rust-sdl2 and there's this Texture struct:
pub struct Texture<'r> {
raw: *mut sys::SDL_Texture,
_marker: PhantomData<&'r ()>,
}
How do I know where the 'r lifetime comes from?
I'm reading the code of rust-sdl2 and there's this Texture struct:
pub struct Texture<'r> {
raw: *mut sys::SDL_Texture,
_marker: PhantomData<&'r ()>,
}
How do I know where the 'r lifetime comes from?
Copyright © 2021 Jogjafile Inc.
If the struct was declared like this, then Rust would be able to automatically ensure memory safety:
Since the
SDL_Textureis managed outside of Rust code this isn't possible because a raw pointer is needed. The lifetime on theTextureis there to add a memory-safe abstraction around an unsafe data structure.The crate manages the creation of
Textures, and ensures that the lifetimes are always "correct". The lifetime is there to ensure that the texture does not outlive the innerSDL_Texture, which is only referenced by raw pointer.You cannot create a
Textureyourself, except by unsafe functions. If you were to callTextureCreator::raw_create_textureyou'd have to meet all requirements on that lifetime yourself. Instead, the safe methodcreate_textureconstructs aTexture, while guaranteeing memory safety.The type signature of
create_textureis:Some lifetimes are elided. According to Rust's lifetime elision rules, this can be written more explicitly as:
The lifetime annotations express a referential dependency between
selfand theTexture. The returnedTextureis therefore not allowed to outlive theTextureCreator.