MST

星途 面试题库

面试题:Rust模式匹配复杂数据解构与trait对象结合的高级应用

假设有如下trait和结构体定义: ```rust 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 process_shapes(shapes: Vec<Box<dyn Shape>>) { // 使用模式匹配,遍历shapes,针对不同形状(Circle或Rectangle), // 打印出形状名称和面积,补全以下代码 for shape in shapes { match shape.as_ref() { // 在此处补全模式匹配代码 } } } ``` 请补全`process_shapes`函数中的模式匹配代码。
22.3万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn process_shapes(shapes: Vec<Box<dyn Shape>>) {
    for shape in shapes {
        match shape.as_ref() {
            Circle { radius } => println!("Circle, Area: {}", std::f64::consts::PI * radius * radius),
            Rectangle { width, height } => println!("Rectangle, Area: {}", width * height),
        }
    }
}