MST
星途 面试题库

面试题:Rust中trait对象与动态分发在函数和方法中的应用

定义一个`trait` `Shape`,包含方法`area`用于计算形状的面积。接着定义两个结构体`Circle`和`Rectangle`,分别实现`Shape` trait。编写一个函数`total_area`,它接受一个`Vec<Box<dyn Shape>>`类型的参数,计算并返回所有形状的总面积。最后,在`main`函数中创建`Circle`和`Rectangle`的实例,并将它们放入`Vec<Box<dyn Shape>>`中,调用`total_area`函数并打印结果。请考虑如何正确处理所有权和生命周期问题,确保代码能够编译并正确运行。
13.5万 热度难度
编程语言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: f64,
    height: f64,
}

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

fn total_area(shapes: Vec<Box<dyn Shape>>) -> f64 {
    shapes.into_iter().map(|s| s.area()).sum()
}

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

    let mut shapes: Vec<Box<dyn Shape>> = Vec::new();
    shapes.push(Box::new(circle));
    shapes.push(Box::new(rectangle));

    let result = total_area(shapes);
    println!("Total area: {}", result);
}