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),
}
}