第 3 章: 复合类型与模式匹配
3.1 复合类型
元组
let tup: (i32, f64, char) = (500, 6.4, 'z');
let (x, y, z) = tup;
println!("x={}, y={}, z={}", x, y, z);
数组与切片
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
3.2 结构体与枚举
结构体
struct Point {
x: f64,
y: f64,
}
impl Point {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
枚举
enum IpAddr {
V4(String),
V6(String),
}
- 枚举适合表示离散状态
- 结合
match 可写出安全分支逻辑
3.3 match 与模式匹配
let num = 13;
match num {
1 => println!("one"),
2..=12 => println!("between two and twelve"),
_ => println!("other"),
}
- 模式可以解构元组、枚举、引用
if 守卫可用于附加条件
3.4 Option 与 Result
Option
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 {
None
} else {
Some(numerator / denominator)
}
}
Result
use std::fs::File;
fn open_file() -> Result<File, std::io::Error> {
File::open("hello.txt")
}
Option 表示存在或不存在
Result 表示成功或错误
3.5 练习
- 实现一个枚举来表示四则运算并计算结果
- 使用
match 处理 Option 和 Result
- 写一个函数返回数组中最大值的
Option