MST

星途 面试题库

面试题:Rust结构体复杂模式匹配及错误处理机制

定义一个Rust结构体`Shape`,它是一个枚举,包含`Circle`(有半径`radius`字段)、`Rectangle`(有`width`和`height`字段)两种变体。编写一个函数,接受`Shape`实例,使用模式匹配计算其面积。如果是`Circle`,面积公式为`π * radius * radius`;如果是`Rectangle`,面积公式为`width * height`。在计算过程中,如果半径或宽高为负数,返回一个合理的错误类型,并在调用函数时妥善处理错误,要求在错误处理中展示`match`的不同分支处理不同错误的情况。
44.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fmt;
use std::error::Error;

// 定义错误类型
#[derive(Debug)]
struct NegativeValueError;

impl fmt::Display for NegativeValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "发现负数")
    }
}

impl Error for NegativeValueError {}

// 定义Shape枚举
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
}

// 计算面积的函数
fn calculate_area(shape: Shape) -> Result<f64, NegativeValueError> {
    match shape {
        Shape::Circle { radius } => {
            if radius < 0.0 {
                Err(NegativeValueError)
            } else {
                Ok(std::f64::consts::PI * radius * radius)
            }
        }
        Shape::Rectangle { width, height } => {
            if width < 0.0 || height < 0.0 {
                Err(NegativeValueError)
            } else {
                Ok(width * height)
            }
        }
    }
}

fn main() {
    let circle = Shape::Circle { radius: 5.0 };
    let rectangle = Shape::Rectangle { width: 4.0, height: 3.0 };
    let negative_circle = Shape::Circle { radius: -2.0 };
    let negative_rectangle = Shape::Rectangle { width: -1.0, height: 2.0 };

    match calculate_area(circle) {
        Ok(area) => println!("圆形面积: {}", area),
        Err(e) => println!("错误: {}", e),
    }

    match calculate_area(rectangle) {
        Ok(area) => println!("矩形面积: {}", area),
        Err(e) => println!("错误: {}", e),
    }

    match calculate_area(negative_circle) {
        Ok(area) => println!("圆形面积: {}", area),
        Err(e) => println!("错误: {}", e),
    }

    match calculate_area(negative_rectangle) {
        Ok(area) => println!("矩形面积: {}", area),
        Err(e) => println!("错误: {}", e),
    }
}