I use the SDL2 crate and I wrote those structures:
pub struct TextureMap<'a> {
textures: Vec<Option<Texture<'a>>>,
texture_creator: TextureCreator<WindowContext> // SDL2 thing to load textures
}
impl<'a> TextureMap<'a>
{
pub fn new(texture_creator: TextureCreator<WindowContext>) -> TextureMap<'a> {
TextureMap { textures: Vec::new(), filenames: Vec::new(), texture_creator: texture_creator }
}
pub fn get_texture(&'a mut self, texture_id: usize) -> &'a Texture {
// Return the texture or load it from its path (which happens to be known)
// (...)
self.textures[texture_id].as_ref().unwrap()
}
}
In that TextureMap struct, I believe the lifetime specifier is needed as the textures musn't outlive the TextureCreator.
Then I have to propagate that specifier to my SpriteStore structure. Understandable since it aggregates the TextureMap.
pub struct SpriteStore<'a> {
store: Vec<Sprite>,
texture_map: TextureMap<'a>
}
impl<'a> SpriteStore<'a>
{
// Loads the store from JSON files at the start of the game (without loading textures)
pub fn new(texture_creator: TextureCreator<WindowContext> ) -> Self {
// ... fills in the structures
}
pub fn render(&'a mut self, canvas: &mut WindowCanvas, sprite_id: usize, x: i32, y: i32) {
let sprite = &self.store[sprite_id];
let tex = self.texture_map.get_texture(sprite.texture_id) ;
let dest_rect = Rect::new(x, y, sprite.src_rect.width(), sprite.src_rect.height());
canvas.copy(&tex, sprite.src_rect, dest_rect).unwrap();
}
}
So when I do something as simple as :
let mut bsc = SpriteStore::new(canvas.texture_creator());
bsc.render(&mut canvas, UserSprites::RedCircle as usize, 100, 100);
It says bsc is borrowed at the second line (OK), and "borrowed value does not live long enough", pointing me to the end of the main() function :
`bsc` dropped here while still borrowed
| borrow might be used here, when `bsc` is dropped and runs the destructor for type `SpriteStore<'_>`
I don't understand this. To me the borrow ends after the render() function returns.
There is no lifetime specifier elsewhere in my code. The Sprite structure is just a rectangle with a texture ID, so it's not the problem.
What do I miss ?
Thank you,