Skip to content

Instantly share code, notes, and snippets.

@pedro-w
Last active June 14, 2017 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedro-w/b04c93892d9d0180475d7836d3014da2 to your computer and use it in GitHub Desktop.
Save pedro-w/b04c93892d9d0180475d7836d3014da2 to your computer and use it in GitHub Desktop.
Help needed with lifetime error

Summary

In Rust SDL2 I need to create a texture. The way to do this is to get a TextureCreator from a Window and then use TextureCreator to create the textures. The TextureCreator lives independently from its Window. However the Texture must not outlive the TextureCreator. I don't know how to encapsulate this in a struct so that the compiler knows that.

The code in main.rs gives error [E0597]

(compiled with stable 1.18)

error[E0597]: `tc` does not live long enough
  --> main.rs:19:19
   |
19 |         let tex = tc.create_texture_streaming(None, 128, 128).unwrap();
   |                   ^^ does not live long enough
...
24 |     }
   |     - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 16:1...
  --> main.rs:16:1
   |
16 | / impl<'a> Thing<'a> {
17 | |     pub fn new(c: &Canvas<Window>) -> Thing<'a> {
18 | |         let tc = c.texture_creator();
19 | |         let tex = tc.create_texture_streaming(None, 128, 128).unwrap();
...  |
24 | |     }
25 | | }
   | |_^
extern crate sdl2;
use sdl2::video;
use sdl2::render;
use sdl2::video::Window;
use sdl2::video::WindowContext;
use sdl2::render::Canvas;
use sdl2::render::TextureCreator;
use sdl2::render::Texture;
struct Thing<'a> {
texture_creator: TextureCreator<WindowContext>,
texture: Texture<'a>,
}
impl<'a> Thing<'a> {
pub fn new(c: &Canvas<Window>) -> Thing<'a> {
let tc = c.texture_creator();
let tex = tc.create_texture_streaming(None, 128, 128).unwrap();
Thing {
texture_creator: tc,
texture: tex,
}
}
}
fn main() {
let sdl = sdl2::init().unwrap();
let sdl_video = sdl.video().unwrap();
let win = sdl_video.window("Test", 320, 240).build().unwrap();
let canvas = win.into_canvas().build().unwrap();
let thing = Thing::new(&canvas);
println!("It's your {:?}", thing.texture.query());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment