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