结构体、枚举和模式匹配
实验环境:rustc / cargo 1.93(Linux),文中代码、报错与输出均为实测。
前面几篇把变量、函数、所有权讲完了。这一篇开始组织数据:定义自己的类型(struct / enum),再用 match 按取值分支。这三样是日常写 Rust 绕不开的。
结构体:给一组相关数据起个名字
struct 和元组类似——都能装多个值,字段可以是不同类型。区别在于 struct 给每个字段起了名字,含义清楚,不用靠"第几个是什么"去记。定义一个存用户信息的:
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
用 struct 加类型名,花括号里写字段名和类型。要用它就得造一个实例——给每个字段填上具体值,顺序不必和声明时一致:
fn main() {
let mut user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
user1.email = String::from("another@example.com"); // 改字段,实例得是 mut
println!("{}", user1.email); // another@example.com
}
注意:想改某个字段,整个实例必须 mut——Rust 不允许只把其中一个字段标成可变。
两个省事的写法:字段初始化简写(参数名和字段名相同时只写一遍)和 struct 更新语法(用 ..user1 把已有实例的其余字段搬过来)。下面这个函数返回一个新的 User,就用了简写:
fn build_user(username: String, email: String) -> User {
User { active: true, username, email, sign_in_count: 1 } // username、email 各写一遍即可
}
方法:在 impl 块里给类型加行为
方法是"绑定到某个类型的函数",用 fn 声明、可以有参数和返回值;和普通函数的区别是它写在结构体的上下文里,第一个参数是 self(或其借用形式),代表被调用的那个实例。写在一个 impl 块中:
#[derive(Debug)]
struct Rectangle { width: u32, height: u32 }
impl Rectangle {
fn area(&self) -> u32 { self.width * self.height } // &self = 借用,不拿走所有权
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("The area of the rectangle is {} square pixels.", rect1.area());
}
// The area of the rectangle is 1500 square pixels.
#[derive(Debug)] 让类型实现 Debug,之后能用 {:?} 把它打印出来调试。方法第一个参数写 &self 表示借用(不转移所有权),正好接上上一篇的借用规则。
方法还能带别的参数——比如拿另一个实例来比较,传引用就行:
impl Rectangle {
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 rect2 = Rectangle { width: 10, height: 40 };
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); // true
}
还有一种关联函数(associated function):不带 self、用类型名加 :: 调用,常用来做构造器。你其实一直在用它——前面每篇里的 String::from(...) 就是 String 的关联函数:
impl Rectangle { fn square(size: u32) -> Self { Self { width: size, height: size } } }
fn main() { let sq = Rectangle::square(3); println!("{sq:?}"); } // Rectangle { width: 3, height: 3 }
枚举:一个值只能是几个选项之一
struct 把相关字段"打包在一起",enum 则是说"这个值只能是几种情况里的某一种"。比如一个 IP 地址要么是 IPv4、要么 IPv6:
#[derive(Debug)]
enum IpAddrKind { V4, V6 }
fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; println!("{four:?} {six:?}"); } // V4 V6
枚举的变体还能携带数据。最典型的是标准库里的 Option<T>——它把"有值 / 没值"建模成一个类型,替代了 C/Java 中的 null:Some(T) 装一个任意类型的值,None 表示没有。Rust 没有 null,其他语言里空指针崩溃的那种情况,在这里变成你必须显式处理的两种情况:
fn main() { let a: Option<i32> = Some(1); let b: Option<i32> = None; println!("{a:?} {b:?}"); } // Some(1) None
<T> 是泛型参数,后面讲。这里只要知道:Some 里能放任何类型,每换一个具体类型就得到一个新的 Option<T>。
match:按取值分支,而且必须穷尽
处理枚举最顺手的控制流结构是 match:拿一个值挨个比对一组模式(pattern),命中哪个就跑哪段代码。它和 if 长得像但更通用——if 的条件必须是 bool,match 的值可以是任意类型。
enum Coin { Penny, Nickel, Dime, Quarter }
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() { println!("{}", value_in_cents(Coin::Quarter)); } // 25
每个分支(arm)是"模式 => 代码",用逗号隔开;match 按顺序比对,命中即执行。关键约束:必须穷尽——每个变体都要覆盖到,漏了直接编译报错:
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5, // 漏了 Dime、Quarter
}
}
error[E0004]: non-exhaustive patterns: `Coin::Dime` and `Coin::Quarter` not covered
这正是 Rust "逼你把每种情况都想全"。真心想说"剩下的都归一类"就用通配符 _;变体携带数据时还能把值绑定到变量——下面用 Option 演示,Some(n) 里的 n 就把里面的值取了出来:
fn main() {
let x: Option<i32> = Some(5);
match x {
Some(n) => println!("got {n}"), // n == 5
None => {}, // None 不带数据,模式就写 None
}
} // got 5
穷尽 + _ + 绑定这三样,日常用 match 处理枚举基本够用。只关心某一个分支时还有更短的写法 if let Some(n) = x { ... },后面单独提;解构元组、结构体等复杂模式属于进阶。
动手实践
把上面的代码逐个敲一遍跑一下,尤其是会报错的那段 match——看 E0004 指出你漏了哪个变体。能自己写出"定义一个 enum,再用 match 处理它所有分支",这篇就算过了。struct / enum / match 是后面内容的地基:Option<T>、Result<T, E>(下一篇错误处理的主角)都是枚举,全靠 match / if let 解包;集合类型 Vec、HashMap 则是下篇的事。