-
Rust 문법: dyn, trait, polymorphism컴퓨터/Rust 2021. 5. 2. 20:50728x90반응형
Rust
1. dyn, trait
trait: unknown 타입 (Self)을 위해 정의된 메서드 collection
doc.rust-lang.org/book/ch10-02-traits.html?highlight=trait#traits-defining-shared-behavior
dyn: dynamic 하게 dispatch 되는 부분을 highlight
(dynamic dispatch to a trait object)
2. 예제 코드
자바/파이썬 개념으로 설명하면
Car, Motocycle이란 클래스가 있고 이 두 클래스는 Vehicle이란 interface를 implement 한다.
각 go()를 실행하면 단순히 message만 출력한다.
Shop이란 클래스는 자동차 종류를 vector(array) 형식으로 저장하고 있다. type은 Vehicle
Box를 이용해서 pointer 변수이다. Shop에 Car, Motorcycle들을 append 시킨다.
move_all을 실행하면 polymorphism 하게 모든 Vehicle를 implement 한 클래스들의 go()를 실행한다.
// A trait is a collection of methods defined for an unknown type: Self. // They can access other methods declared in the same trait. // The dyn keyword is used to highlight that calls to methods on the associated // Trait are dynamically dispatched. To use the trait this way, it must be 'object safe'. trait Vehicle { fn go(&self); } struct Car; struct Motorcycle; impl Vehicle for Car { fn go(&self) { println!("Hello, Car is moving!"); } } impl Vehicle for Motorcycle { fn go(&self) { println!("Hello, Motorcycle is moving!"); } } impl Car { fn new() -> Car { Car } } impl Motorcycle { fn new() -> Motorcycle { Motorcycle } } struct Shop { cars: Vec<Box<dyn Vehicle>>, } impl Shop { fn new() -> Shop { Shop { cars: Vec::new() } } fn add_car(&mut self, car: Box<dyn Vehicle>) { self.cars.push(car); } fn move_all(&self) { for car in &self.cars { car.go(); } } } fn main() { let mut shop = Shop::new(); shop.add_car(Box::new(Car::new())); shop.add_car(Box::new(Motorcycle::new())); shop.move_all(); // let mut vec: Vec<Box<dyn Vehicle>> = vec![]; // let car = Car::new(); // let motor = Motorcycle::new(); // vec.push(Box::new(car)); // vec.push(Box::new(motor)); // for vehicle in &vec { // vehicle.go(); // } }
# 결과 Hello, Car is moving! Hello, Motorcycle is moving!
728x90'컴퓨터 > Rust' 카테고리의 다른 글
could not find native static library mysqlclient 오류 해결법 (0) 2021.07.10 Rust 문법: Ownership (소유권) (0) 2021.04.24 Rust: PyO3 파이썬 모듈 Rust 언어로 만들기 (0) 2021.04.24