0

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 aBox` 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.

  • I think this is a difficult question to answer without knowing more about your architecture. Did you write `Engine`? If so maybe you should consider making `sound` and `renderer` private variables that way `Engine` can just own everything. – etchesketch Dec 21 '22 at 15:58
  • The visibility of the structs and their fields does not affect the issue. – Lucas S. Dec 21 '22 at 16:59
  • @LucasS. you are correct. I thought that by making the variables private we could create a `new( context: Context ) -> Engine` function and create the `sound` and `renderer` objects in there. That only pushes the problem out another level though it doesn't solve anything. – etchesketch Dec 21 '22 at 19:36
  • I'm not sure there are very many solutions to this problem other than "use smart pointers" or "rewrite to not store references". – etchesketch Dec 21 '22 at 19:48
  • Thanks for the comments everyone, it seems like the only solution is to take another approach. I think the first comment is the one most applicable to what most people clicking on this would be trying to achieve. – Lachlan Munday Dec 22 '22 at 11:39

0 Answers0