i'm pretty new to Rust and am trying to make a simple Sdl2 game-engine using it as my first proper project. I got the renderer and audio system working on their own, and am trying to integrate it with the Engine when I ran into the problem described below. At first I initialised the renderer and sound system in seperate functions, but that was only for testing and was not the solution I was happy with. Ideally, this is how the code will end up but I cannot seem to get it working. I understand the error message, but I do not know how to fix it without having to make compromises.
fn new() -> Result<Engine<'a>, String> {
// The SDL2 context is required to get the video and audio subsystems
let context: Sdl = sdl2::init()?;
// Renderer takes a &Sdl as the first parameter
let renderer = Renderer::new(&context, "Sdl2 Engine", 800, 600)?;
// Sound also take &Sdl as the first parameter
let sound = Sound::new(&context)?;
Ok(Engine { context, renderer, sound })
}
When I try to compile this code, I receive the error: cannot return value referencing local variable context
returns a value referencing data owned by the current function
I tried wrapping the context in a
Box` but that made no difference. And although putting the initialisation of the video and audio system into seperate functions did work, it is not the solution I intended to use, and required me to wrap the systems in a refCell and option, which considering how often these values will be accessed, would end up being a performance issue in the future. Any help would be greatly appreciated.