Hey I cannot wrap my head around lifetimes in Rust
Can someone explain to me why this does not work and how to build something like this? I'm trying to build a "cache" for textures (I'm using SDL2) that loads the texture into memory if it was not previously accessed.
My TextureManager
pub struct TextureManager<'a> {
texs: HashMap<String, Texture<'a>>,
creator: TextureCreator<WindowContext>,
}
impl <'a: 'b, 'b> TextureManager<'a> {
pub fn new(creator: TextureCreator<WindowContext>) -> Self {
TextureManager { texs: HashMap::new(), creator }
}
pub fn get(&'a mut self, name: String) -> &'b Texture<'a> {
let m = &mut self.texs;
if m.contains_key(&name) {
return m.get(&name).unwrap()
} else {
let tex = self.creator.load_texture(format!("assets/{}", name)).unwrap();
m.insert(name.clone(), tex).unwrap();
return m.get(&name).unwrap()
}
}
}
How I try to use it in the render loop
let mut tex_manager = TextureManager::new(canvas.texture_creator());
'running: loop {
...
for rp in hotel.rooms.iter() {
...
let texture = tex_manager.get(room.sprite());
canvas.copy(&texture, sprite, screen_rect)?;
}
...
}
The error message:
error[E0499]: cannot borrow `tex_manager` as mutable more than once at a time
--> src/main.rs:151:27
|
151 | let texture = tex_manager.get(room.sprite());
| ^^^^^^^^^^^ `tex_manager` was mutably borrowed here in the previous iteration of the loop
...
163 | }
| - first borrow might be used here, when `tex_manager` is dropped and runs the destructor for type `TextureManager<'_>`