MST

星途 面试题库

面试题:Rust中match表达式在处理枚举类型时的应用

假设有一个枚举类型`enum Shape { Circle(f64), Rectangle(f64, f64), Triangle(f64, f64) }`,请使用`match`表达式实现一个函数`calculate_area`,该函数接收一个`Shape`类型的参数,并返回该形状的面积。圆的面积公式为`πr²`,矩形面积为长乘宽,三角形面积为`0.5 * 底 * 高`。
38.5万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

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

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

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