0

The idea is simple: there are some Apps which have some Windows. Windows have some type of reference to their app. They need to use each-others methods. I've made some sketchy code, but when I resolve one issue I get a new one.

struct Win {
      x: i32,
      y: i32,
      last_event: u32, // just for testing
      app: App,
}

impl Win {
    pub fn new(app: &mut App, x: i32, y: i32) -> Win {
        let mut win = Win{app: *app, x: x, y: y, last_event: 0};
        app.add_window(&mut win);
        win
    }

    fn add_window_to_app(&mut self, app: &mut App) {
        app.add_window(self);
    }

    pub fn on_event(&mut self, event: u32, param1: u32, param2: u32) {
        self.last_event = event;
    }
}

struct App {
    pid: u32,
    windows: Vec<Win>,
}

impl App {
    pub fn new(pid: u32) -> App {
        let app = App{pid: pid, windows: Vec::<Win>::new()};
        app
    }

    pub fn add_window(&mut self, win: &mut Win) {
        self.windows.push(*win);
    }

    pub fn on_event(&mut self, win: &mut Win, event: u32, param1: u32, param2: u32) {
        win.on_event(event, param1, param2);
    }
}

fn main() {
    let mut app = App::new(1);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Revertron
  • 1,213
  • 2
  • 13
  • 17

1 Answers1

1

Ideal: sort your dependency graph to make acyclic, then the borrow checks will work out of the box.


Practical: because reality tends to be more complicated than desired, the ideal situation can be either impossible or impractical. In this case, you can move the ownership check from compile-time to run-time by using RefCell (from std::cell).

This still forbids aliasing + mutability (so you cannot mutate a Win to which you already have a reference in use elsewhere), but defer to check to run-time, at a small penalty.


Callback Hell: implement a broker, who owns both Wins and Apps, and have the Win/App refer to each other via IDs; when interaction is needed, the Win/App sends an event to the broker which is treated asynchronously.

This disentangle the ownership graph at the cost of getting a callback hell.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722