0

I decided to do a really simple game loop by looping over a Vec of traits. Because a trait size is unknown, I need to use a Box or a reference to achieve this polymorphic approach. My approach may not be the right one to achieve this.

I tried with a Box:

trait Renderable {
    fn update(&mut self);
}

struct Game {
    renderables: Vec<Box<Renderable>>,
}

impl Game {
    fn new() -> Game {
        Game {
            renderables: Vec::new(),
        }
    }

    fn update(&mut self) {
        for mut it in &self.renderables {
            it.update();
        }
    }
}

fn main() {
    let mut g = Game::new();

    g.update();
}
error[E0596]: cannot borrow immutable `Box` content `**it` as mutable
  --> src/main.rs:18:13
   |
18 |             it.update();
   |             ^^ cannot borrow as mutable

I tried with references:

trait Renderable {
    fn update(&mut self);
}

struct Game<'a> {
    renderables: Vec<&'a mut Renderable>,
}

impl<'a> Game<'a> {
    fn new() -> Game<'a> {
        Game {
            renderables: Vec::new(),
        }
    }

    fn update(&mut self) {
        for it in &self.renderables {
            it.update();
        }
    }
}

fn main() {
    let mut g = Game::new();

    g.update();
}
error[E0389]: cannot borrow data mutably in a `&` reference
  --> src/main.rs:18:13
   |
18 |             it.update();
   |             ^^ assignment into an immutable reference
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lunfel
  • 2,499
  • 21
  • 29
  • 2
    `for it in &mut self.renderables` – Boiethios Jul 18 '18 at 07:30
  • Also, note that now, we must note trait objects with `dyn`: `Box` – Boiethios Jul 18 '18 at 08:11
  • Thanks @Boiethios, this worked for me. I know that it is a duplicate, but I tried the other answer with iter() and it didn't work. – Lunfel Jul 18 '18 at 18:05
  • So just to understand what is going on, in a for loop the `&mut` is applied to each individual elements of the Vec and not the Vec itself? – Lunfel Jul 18 '18 at 18:06
  • 1
    Look at `AsMut`: https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-AsMut%3C%5BT%5D%3E It is like an overload of `&mut` operator. – Boiethios Jul 18 '18 at 20:30

0 Answers0