0

New to , I'm trying my hand at a simple project.

I want to create a Sprite struct to hold the surface & texture to display a simple image.

My attempt so far:

pub struct Sprite<'a> {
    //surface : sdl2::surface::Surface<'a>,
    texture : sdl2::render::Texture<'a>,
}

impl Sprite<'_> {
    pub fn new<'a, P: AsRef<std::path::Path>>(
        canvas: &mut sdl2::render::WindowCanvas,
        path: P
        ) -> Result<Sprite<'a>, String>
    {
        let surface = sdl2::surface::Surface::load_bmp(path)?;
        let texture_creator = canvas.texture_creator();
        let texture = texture_creator.create_texture_from_surface(&surface).unwrap();

        Ok(Sprite {
            //surface,
            texture,
        })
    }
}

Sadly, texture_creator gets borrowed by the create_texture_from_surface call which gives me:

error[E0515]: cannot return value referencing local variable texture_creator

I don't know how to work around this issue and need help to understand it

Jaffa
  • 12,442
  • 4
  • 49
  • 101
  • Your `texture` references `surface`. So if you return both `surface` and `texture`, `surface` moves in memory while `texture` references the old address, creating a dangling reference. Rust does not allow this, and therefore you can't do this. For more info, read this: https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct – Finomnis Feb 23 '23 at 10:49
  • Thanks for the answer and the link @Finomnis. I tried removing the `surface` attribute from the struct (I don't really need it), but the error is still the same. The only way I found to make it work was to create the texture each time I need to display it, which seems needlessly wasteful – Jaffa Feb 23 '23 at 11:10
  • The error is still the same because it still references a local variable. This isn't a compiler error in other languages like C/C++, but still undefined behavior. Let me reproduce your problem and see if I can come up with better advice. – Finomnis Feb 23 '23 at 12:01
  • 1
    @Finomnis I'm coming up with something, I need to keep the reference to the texture_creator in a place that owns the sprite so its lifetime is bigger than the sprite. – Jaffa Feb 23 '23 at 12:11
  • @Finomnis can you post your initial comment as an answer so I can accept it? – Jaffa Feb 23 '23 at 12:11
  • 1
    If that's a valid answer for you, let me mark it as a duplicate. – Finomnis Feb 23 '23 at 12:14

0 Answers0