Menu
CoddyTech

回顾:Shape 枚举

本课属于 Coddy Rust 学习旅程的“面向对象编程”单元。第 18 课,共 61 课。

challenge icon

挑战

简单

我们来构建一个几何计算器,用枚举表示不同的形状,每种形状都存储自己的尺寸。你的 Shape 枚举将展示单一类型如何保存不同的数据结构,并通过方法提供统一的行为。

你将创建两个文件来组织代码:

  • shape.rs:定义一个公开的 Shape 枚举,包含两个变体:
    • Circle:包含一个表示半径的 f64(元组语法)
    • Rectangle:包含命名字段:width(f64)和 height(f64)
    实现一个 area 方法,通过模式匹配根据变体计算正确的面积。对于圆,使用 3.14159 作为 π。
  • main.rs:引入你的形状模块,使用提供的输入创建每种形状变体的一个实例,并打印每种形状的面积。

你的 area 方法应返回一个 f64。匹配时,解构每个变体以提取其尺寸,并应用相应的公式:

  • 圆的面积:π × radius²
  • 矩形的面积:width × height

输出应将每种形状的面积各自显示在一行中,并且恰好保留一位小数:

Circle area: {area}
Rectangle area: {area}

例如,圆的半径为 5.0,矩形的宽为 4.0、高为 6.0 时,输出如下:

Circle area: 78.5
Rectangle area: 24.0

你将收到三个输入:圆的半径、矩形的宽和矩形的高。

亲手试试

mod shape;

use shape::Shape;

fn main() {
    // 读取输入
    let mut radius_input = String::new();
    std::io::stdin().read_line(&mut radius_input).expect("Failed to read line");
    let radius: f64 = radius_input.trim().parse().expect("Invalid number");

    let mut width_input = String::new();
    std::io::stdin().read_line(&mut width_input).expect("Failed to read line");
    let width: f64 = width_input.trim().parse().expect("Invalid number");

    let mut height_input = String::new();
    std::io::stdin().read_line(&mut height_input).expect("Failed to read line");
    let height: f64 = height_input.trim().parse().expect("Invalid number");

    // TODO:用 radius 创建一个 Circle 形状
    
    // TODO:用 width 和 height 创建一个 Rectangle 形状
    
    // TODO:输出每个形状的面积,保留一位小数
    // 格式:“Circle area: {area}”和“Rectangle area: {area}”
}

面向对象编程中的所有课

自己练习: Rust 在线编译器