I am trying to implement update and component pattern in rust.
So far I have got this solution, which requires cloning the components. Is there a more efficient way without cloning?
Or is there actually some different better solution in rust to implement update and component patterns?
I would like to have the component to be mutable in update method.
use std::cell::RefCell;
use std::rc::Rc;
trait Component{
fn update(&mut self, &mut Actor);
}
struct Actor{
x : i32,
y : i32,
cmps : Vec<Rc<RefCell<Component>>>,
}
impl Actor{
fn new() -> Self{
Actor{
x : 0,
y : 0,
cmps : vec![Rc::new(RefCell::new(Mover::new()))],
}
}
fn display(&self){
println!("{}:{}",self.x, self.y);
}
fn update(&mut self){
// this is where I need to clone components to be able
// to pass self as mutable reference
let mut cmps = self.cmps.clone();
for cmp in cmps.iter_mut(){
cmp.borrow_mut().update(self);
}
}
}
struct Mover{
x : i32,
y : i32,
}
impl Mover{
fn new() -> Self{
Mover{
x : 3,
y : 2,
}
}
}
impl Component for Mover{
fn update(&mut self,actor : &mut Actor){
actor.x += self.x;
actor.y += self.y;
let tmp = self.x;
self.x = self.y;
self.y = tmp;
}
}
fn main() {
let mut actor = Actor::new();
for _ in 1..10{
actor.display();
actor.update();
}
}
Thanks for help
Aucun commentaire:
Enregistrer un commentaire