MST

星途 面试题库

面试题:Rust类型别名在Trait对象与生命周期管理中的优化

给定一个包含多个不同类型但都实现了同一个trait的对象集合,例如 `trait Drawable { fn draw(&self); }`,有 `struct Circle { radius: f32 }` 和 `struct Rectangle { width: f32, height: f32 }` 都实现了 `Drawable`。使用类型别名来简化处理这个集合的代码,同时要正确处理生命周期问题,避免悬垂引用。请写出完整的代码实现,包括集合的定义、类型别名、相关函数以及必要的生命周期标注。
23.0万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait Drawable {
    fn draw(&self);
}

struct Circle {
    radius: f32,
}

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

struct Rectangle {
    width: f32,
    height: f32,
}

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

// 使用类型别名简化处理集合的代码
type DrawableList<'a> = Vec<&'a dyn Drawable>;

fn draw_all(drawables: &DrawableList) {
    for drawable in drawables {
        drawable.draw();
    }
}

fn main() {
    let circle = Circle { radius: 5.0 };
    let rectangle = Rectangle { width: 10.0, height: 5.0 };

    let mut drawables: DrawableList = Vec::new();
    drawables.push(&circle);
    drawables.push(&rectangle);

    draw_all(&drawables);
}