MST
星途 面试题库

面试题:Rust中trait方法的定义与实现及调用

定义一个 `Shape` trait,其中包含一个计算面积的方法 `area`。然后定义 `Circle` 和 `Rectangle` 两个结构体,实现 `Shape` trait。在 `main` 函数中,创建 `Circle` 和 `Rectangle` 的实例,并将它们放入一个 `Vec<Box<dyn Shape>>` 向量中,通过遍历向量调用 `area` 方法输出各个形状的面积。假设 `Circle` 结构体有一个 `radius` 字段(`f64` 类型),`Rectangle` 结构体有 `width` 和 `height` 字段(`u32` 类型)。
27.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }
}

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

impl Shape for Rectangle {
    fn area(&self) -> f64 {
        (self.width * self.height) as f64
    }
}

fn main() {
    let mut shapes: Vec<Box<dyn Shape>> = Vec::new();
    shapes.push(Box::new(Circle { radius: 5.0 }));
    shapes.push(Box::new(Rectangle { width: 10, height: 5 }));

    for shape in shapes {
        println!("Area: {}", shape.area());
    }
}