Badly stuck on how to deal with lifetimes and make this compile

I'm trying to write an emulator in rust to learn the language, but i've gotten stuck.
Basically I'm trying to add a gui to the program and the gui needs to have a reference to a Machine struct that holds variable representing RAM, CPU registers etc.

I then want to do run the emulation and as the data updates have the gui update using it's reference to the machine data.

Something like this...

However I don't know how to write a function start_gui() method that will compile.

When I try to do anything with the machine variable in the start__gui() function, It complains about "explicit lifetime required" and to use static I read up on lifetimes but I guess I didn't understand what I read as I still have no idea what to do to make it compile.

How do i write a function that can read from the struct in the variable machine? It just has to read the data, any changes will be done in the loop section.

use chip8_gui::*;
use chip8::*;

fn main() {
  let rom_file_name = "test.rom";
  let mut machine = c8::machine::new_machine(rom_file_name);

Chip8Gui::start_gui(&machine);
  loop {
    // do things with machine
  }
}

In Rust a shared reference is supposed to guarantee immutability, so you can't hold a shared reference to something and also mutate it. You have two options:

  • Have your GUI only take a reference to the type when it is updating the GUI. So you will pass this shared reference in whenever you need it, but otherwise it's not present and thus you are free to mutate the object. This is the better method of the two.
  • Use interior mutability; store an &RefCell<Machine>. This will allow you to have a shared reference to the machine which can be mutated while the shared reference exists, as long as mutation is not done at the same time as reading.
2 Likes

Thank you, I'll need to read up on interior mutability, but what you said makes sense.

Really enjoying this language so far!