Rust의 일반 객체들은 전부 스택 구역에 저장된다. 명시적으로 Heap영역에 저장하는 방법은 Box<T>모듈을 쓰는 방법이다.
Box모듈을 쓰면 흔히 C++이나 Java같은 부모 클래스 레퍼런스 변수에 자식 객체를 넣는 것과 비슷한 행동을 할 수 있다.
trait Unit:'static + Sync{
// add code here
fn update(&mut self);
fn draw(&self, dc:&mut DrawContext);
}
#[derive(Debug)]
struct Marine{
}
impl Unit for Marine {
// add code here
fn update(&mut self){
println!("{:?}",self);
}
fn draw(&self, dc:&mut DrawContext){
}
}
#[derive(Debug)]
struct SiegeTank{
}
impl Unit for SiegeTank {
// add code here
fn update(&mut self){
println!("{:?}",self);
}
fn draw(&self, dc:&mut DrawContext){
}
}
fn main() {
let mut unit_list = Vec::<Box<Unit>>::new();
unit_list.push(Box::new(SiegeTank{}));
unit_list.push(Box::new(Marine{}));
unit_list.push(Box::new(SiegeTank{}));
unit_list.push(Box::new(Marine{}));
for mut it in &mut unit_list{
it.update();
}
}
결과
SiegeTank
Marine
SiegeTank
Marine
댓글 0