MST
星途 面试题库

面试题:Rust 泛型结构体在 trait 上下文中的类型推导与高级应用

定义一个 trait `Drawable`,它有一个方法 `draw`。接着定义一个泛型结构体 `ShapeContainer`,它可以存储实现了 `Drawable` trait 的任何类型的形状。实现一个函数 `draw_all`,它接收一个 `ShapeContainer` 实例,并调用其中所有形状的 `draw` 方法。在这个过程中,要求通过类型推导,在 `ShapeContainer` 结构体定义、`draw_all` 函数实现以及调用 `draw_all` 函数时,尽量减少显式类型标注,同时确保代码在不同类型的形状(如自定义的 `Circle`、`Rectangle` 结构体等都实现 `Drawable` trait)下能正确编译和运行。请写出完整的代码示例。
39.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

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

// 定义Circle结构体并实现Drawable trait
struct Circle {
    radius: f64,
}

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

// 定义Rectangle结构体并实现Drawable trait
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);
    }
}

// 定义泛型结构体ShapeContainer
struct ShapeContainer<T>
where
    T: Drawable,
{
    shapes: Vec<T>,
}

// 实现draw_all函数
fn draw_all<T>(container: ShapeContainer<T>)
where
    T: Drawable,
{
    for shape in container.shapes {
        shape.draw();
    }
}

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

    let mut container = ShapeContainer {
        shapes: Vec::new(),
    };
    container.shapes.push(circle);
    container.shapes.push(rectangle);

    draw_all(container);
}