我决定通过循环一个特征来做一个非常简单的游戏循环Vec
。因为特征大小是未知的,所以我需要使用一个Box
或一个引用来实现这种多态方法。我的方法可能不是实现这一目标的正确方法。
我试过一个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
我试过参考:
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