MST

星途 面试题库

面试题:Rust特征的中级应用问题

在Rust中,假设有一个特征`Drawable`,包含一个方法`draw`。现在有两个结构体`Circle`和`Rectangle`都实现了`Drawable`特征。请编写代码展示如何将这两个结构体的实例放入一个`Vec`中,并通过遍历`Vec`调用它们的`draw`方法。
34.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义 Drawable 特征
trait Drawable {
    fn draw(&self);
}

// Circle 结构体实现 Drawable 特征
struct Circle {
    radius: f64,
}

impl Drawable for Circle {
    fn draw(&self) {
        println!("Drawing a circle with radius {}", self.radius);
    }
}

// Rectangle 结构体实现 Drawable 特征
struct Rectangle {
    width: f64,
    height: f64,
}

impl Drawable for Rectangle {
    fn draw(&self) {
        println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
    }
}

fn main() {
    // 创建 Circle 和 Rectangle 的实例
    let circle = Circle { radius: 5.0 };
    let rectangle = Rectangle { width: 10.0, height: 5.0 };

    // 创建一个 Vec<&dyn Drawable> 并放入 Circle 和 Rectangle 的实例
    let mut drawables: Vec<&dyn Drawable> = Vec::new();
    drawables.push(&circle);
    drawables.push(&rectangle);

    // 遍历 Vec 并调用 draw 方法
    for drawable in drawables {
        drawable.draw();
    }
}