有没有一种方法可以使用rust-sdl2在结构内存储纹理?

时间:2019-05-09 03:00:52

标签: rust sdl-2 borrow-checker

我使用rust-sdl2板条箱在窗口屏幕上绘制缓冲区,所以我决定抽象SDL调用。我试图遵循rust-sdl2存储库中的this example,但我的第一想到就是创建类似这样的东西:

pub struct SDLDisplay {
    sdl_context: Sdl,
    video_subsystem: VideoSubsystem,
    canvas: WindowCanvas,
    texture_creator: TextureCreator<sdl2::video::WindowContext>,
    texture: Texture,
}

impl SDLDisplay {
    pub fn new() -> Result<SDLDisplay, String> {
        let sdl_context = sdl2::init()?;
        let video_subsystem = sdl_context.video()?;

        let window = video_subsystem
            .window("Test App", 256, 240)
            .position_centered()
            .build()
            .map_err(|e| e.to_string())?;

        let canvas = window.into_canvas().build().map_err(|e| e.to_string())?;

        let texture_creator = canvas.texture_creator();
        let texture = texture_creator
            .create_texture_streaming(Some(ARGB8888), 256, 240)
            .map_err(|e| e.to_string())?;

        Ok(SDLDisplay {
            sdl_context,
            video_subsystem,
            canvas,
            texture_creator,
            texture,
        })
    }
}

第一个问题是Texture需要一个生命周期参数;我通过在整个代码库中分散一个<'a>来解决了这个问题……它不再抱怨,但是现在我有了以下内容:

error[E0515]: cannot return value referencing local variable `texture_creator`
   |
  --> src/sdl_display.rs:44:9
40 |           let texture = texture_creator
   |                         --------------- `texture_creator` is borrowed here
   |
...
40 |           let texture = texture_creator
44 | /         Ok(SDLDisplay {
   |                         --------------- `texture_creator` is borrowed here
45 | |             sdl_context,
...
46 | |             video_subsystem,
44 | /         Ok(SDLDisplay {
47 | |             canvas,
45 | |             sdl_context,
48 | |             texture_creator,
46 | |             video_subsystem,
49 | |             texture,
47 | |             canvas,
48 | |             texture_creator,
49 | |             texture,
50 | |         })
   | |__________^ returns a value referencing data owned by the current function

50 | |         })
   | |__________^ returns a value referencing data owned by the current function

它告诉我不能将texture_creator移到新结构,因为它是借来创建纹理的,但是如果我在结构内没有TextureCreator实例,它会抱怨说Texture不能超过TextureCreator

我在这里完全迷路了。有没有一种方法可以使用rust-sdl2在结构内部实际存储纹理?

0 个答案:

没有答案