文章目录
结构体实战:用Rust编写矩形面积计算器
让我们通过一个生动的例子来探索Rust结构体的强大功能!我们将创建一个矩形面积计算器,逐步展示如何使用结构体组织相关数据。
📐 问题描述
计算不同尺寸矩形的面积,并优雅地展示计算结果。我们将经历三个进化阶段:
- 基础版:使用独立变量
- 进阶版:使用元组
- 终极版:使用结构体
1️⃣ 基础版:独立变量(混乱版)
fn main() {
let width = 30;
let height = 50;
println!(
"矩形面积:{} 平方像素",
calculate_area(width, height)
);
}
fn calculate_area(w: u32, h: u32) -> u32 {
w * h
}
矩形面积:1500 平方像素
🚨 问题:参数之间没有明确关联,代码可读性差
2️⃣ 进阶版:使用元组
fn main() {
let rect = (30, 50);
println!(
"矩形面积:{} 平方像素",
calculate_area(rect)
);
}
fn calculate_area(dimensions: (u32, u32)) -> u32 {
dimensions.0 * dimensions.1
}
矩形面积:1500 平方像素
⚠️ 改进:数据被分组了
⚠️ 新问题:dimensions.0
是什么?宽度还是高度?不直观!
3️⃣ 终极版:使用结构体(优雅版)
// 定义矩形结构体
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// 关联函数:创建正方形
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
// 方法:计算面积
fn area(&self) -> u32 {
self.width * self.height
}
// 方法:检查是否能容纳另一个矩形
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
// 创建矩形实例
let rect1 = Rectangle {
width: 30,
height: 50,
};
// 创建正方形
let square = Rectangle::square(25);
// 调试打印
println!("📐 rect1结构详情:{:#?}", rect1);
println!("🔲 正方形结构:{:?}", square);
// 计算面积
println!("📏 矩形面积:{} 平方像素", rect1.area());
println!("⬜ 正方形面积:{} 平方像素", square.area());
// 高级调试
let scale = 2;
let debug_rect = Rectangle {
width: dbg!(30 * scale), // 实时调试表达式
height: 50,
};
dbg!(&debug_rect); // 打印完整结构体
// 矩形包含检测
println!("rect1能容纳正方形吗? {}", rect1.can_hold(&square));
}
🎯 运行结果
📐 rect1结构详情:Rectangle {
width: 30,
height: 50,
}
🔲 正方形结构:Rectangle { width: 25, height: 25 }
📏 矩形面积:1500 平方像素
⬜ 正方形面积:625 平方像素
[src/main.rs:40] 30 * scale = 60
[src/main.rs:43] &debug_rect = Rectangle {
width: 60,
height: 50,
}
rect1能容纳正方形吗? true
💡 结构体编程优势
- 语义清晰:字段命名使数据含义一目了然
- 功能封装:相关方法直接与数据结构绑定
- 调试友好:
#[derive(Debug)]
自动实现调试打印dbg!
宏精确追踪表达式值
- 扩展性强:轻松添加新方法(如
can_hold
)
🔍 关键语法解析
// 定义结构体
struct MyStruct {
field1: Type,
field2: Type,
}
// 实现方法
impl MyStruct {
// 关联函数(静态方法)
fn new() -> Self { /* ... */ }
// 实例方法
fn method(&self) { /* ... */ }
}
// 自动派生功能
#[derive(Debug)] // 启用调试打印
掌握了结构体,你就拥有了在Rust中组织复杂数据的超能力!💪🏻 尝试给你的结构体添加更多方法,比如计算周长或绘制图形功能吧!