Not find way work with Rust using function


All the time I try move parts of code to function get to complicated battle with Rust.
So explain please how I can implement handleEvent function in my code?
Link to repo here
Commented code in loop work (


What’s the problem? Are you getting problems because handleEvent receives &self rather than &mut self?

In that case, Rust is trying to “protect” you from accidentally ending your SDL context while you are working with it. There’s an annoying problem with Rust that the compiler always assumes that a struct, or a &mut reference to it, can always free all of its members, which includes your sdl_cntx.

The way this problem is typically solved is that you pass references to critical members from the outside. Because Sdl works with ordinary aliasable &Sdl references, you should give the struct Game such a reference.

If you directly try to add one, rustc will complain about a “missing lifetime specifier”. The problem is that you always have to specify the lifetimes of references in structs, so you have to do something like:

struct Game<'sdl> {
    pub screen: Renderer,
    pub g_running: bool,      
    pub sdl_cntx: &'sdl Sdl

You then have to pass the a reference to the result of sdl2::init to the constructor. If this gets too annoying, you can create an “ST-style” wrapper:

fn with_game<F>(title: &'static str, width: i32, height: i32, f: F)
        where F: for<'sdl> FnOnce(Game<'sdl>) {
    let sdl_init = sdl2::init(sdl2::INIT_VIDEO).unwrap();
    let window = Window::new(title,
    let renderer = Renderer::from_window(window,
    f(Game { screen: renderer, g_running: true, sdl_cntx: &sdl_init })

I used ok instead of matching on Result - you can still get the stack trace.

You can then call it with closure syntax, i.e.

with_game("My Game", 640, 480, |game| {
    // do game stuff.


Dont`t look clear for me ( I see there not easy to slice code in functions


My question were more about how it is going to be to refactor code and move parts os program in function. It seems this is overwhelmed in Rust.