I’m new to rust and learning SDL2 at the same time (please forgive any errors and skipping of error handling). I’ve come across this scenario with mutable borrowing and named lifetimes, and after much googling I cannot find an answer.
In my code I’ve create a struct to be my SDL2 texture repository so that I can use them later. SDL2 and rust say that I need to give a named lifetime for the textures that I’m storing.
// Texture repository to create an store textures
pub struct TextureRepository<'a> {
texture_creator: TextureCreator<WindowContext>,
textures: Vec<Texture<'a>>
}
impl<'a> TextureRepository<'a> {
pub fn new(texture_creator: TextureCreator<WindowContext>) -> Self {
TextureRepository {
texture_creator,
textures: Vec::new()
}
}
pub fn add_texture(&'a mut self, path: &str) {
let texture = self.texture_creator.load_texture(path).unwrap();
self.textures.push(texture);
}
}
When I try to call the add_texture
method from a mutable reference in a function, the compiler complains with:
error[E0499]: cannot borrow
*texture_repository
as mutable more than once at a time
fn main() {
// Do SLD2 setup stuff here...
// ...
// Setup textures
let texture_creator: TextureCreator<WindowContext> = canvas.texture_creator();
let mut texture_repository: TextureRepository = TextureRepository::new(texture_creator);
set_textures(&mut texture_repository);
}
fn set_textures<'a>(texture_repository: &'a mut TextureRepository<'a>) {
texture_repository.add_texture("../../textures/character_1.png");
texture_repository.add_texture("../../textures/character_2.png");
// I get an error with this line above
}
If I call the add_texture
method from the main function from the owning var instead, there are no problems:
fn main() {
// Do SLD2 setup stuff here...
// ...
// Setup textures
let texture_creator = canvas.texture_creator();
let mut texture_repository = TextureRepository::new(texture_creator);
texture_repository.add_texture("../../textures/character_1.png");
texture_repository.add_texture("../../textures/character_2.png");
}
I don’t really want to be transferring around ownership to use the add_texture
method unless I have to. And I want to keep my code structured and concise.
How can I make my set_textures
function work? I’ve tried reborrowing and moving around into different scopes etc. But it just complains about the lifetime. It seems by using a named lifetime I can only mutably borrow once. From what I’ve read/understood: if I didn’t have to name the lifetime, then the second borrow would automatically become a different lifetime (compiler magic)??
How can I do this when you have to use a named lifetime?
FYI the struct for texture from the SDL2 lib looks like this
pub struct Texture<'r> {
raw: *mut SDL_Texture,
_marker: PhantomData<&()>,
}