MST
星途 面试题库

面试题:Rust枚举类型关联数据与复杂模式匹配

定义一个`Shape`枚举,包含`Circle`(关联一个`f64`类型的半径)、`Rectangle`(关联两个`f64`类型的长和宽)两个变体。编写一个函数`calculate_area`,该函数接收一个`Shape`类型的参数,通过模式匹配计算并返回对应形状的面积。圆的面积公式为 `π * r * r`,矩形面积公式为 `长 * 宽`。
12.3万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::f64::consts::PI;

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn calculate_area(shape: Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => PI * radius * radius,
        Shape::Rectangle(length, width) => length * width,
    }
}