45 lines
995 B
Rust
45 lines
995 B
Rust
// Определяем типаж Draw
|
|
trait Draw {
|
|
fn draw(&self);
|
|
}
|
|
|
|
// Структура Circle
|
|
struct Circle;
|
|
|
|
// Реализация Draw для Circle
|
|
impl Draw for Circle {
|
|
fn draw(&self) {
|
|
println!("Drawing circle")
|
|
}
|
|
}
|
|
|
|
// Структура Square
|
|
struct Square;
|
|
|
|
// Реализация Draw для Square
|
|
impl Draw for Square {
|
|
fn draw(&self) {
|
|
println!("Drawing square")
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
// Создаем гетерогенную коллекцию фигур
|
|
let shapes: Vec<Box<dyn Draw>> = vec![Box::new(Circle), Box::new(Square)];
|
|
|
|
// Рисуем все фигуры
|
|
for shape in shapes {
|
|
shape.draw();
|
|
}
|
|
|
|
// Добавим еще фигур динамически
|
|
let mut more_shapes: Vec<Box<dyn Draw>> = Vec::new();
|
|
more_shapes.push(Box::new(Circle));
|
|
more_shapes.push(Box::new(Square));
|
|
|
|
println!("\nЕще фигуры:");
|
|
for shape in more_shapes {
|
|
shape.draw();
|
|
}
|
|
}
|