match 表达式与枚举
Coddy 面向 C# 开发者的 Rust 课程的第 9 课,共 48 课。
C# 枚举是一个带名称的整数值,因此 switch 通常会有一个默认分支,用来处理未命名的底层值。Rust 枚举可以让不同变体携带不同的数据。匹配 Rust 枚举时,会检查所有变体,并提取各个分支中类型已知的负载。C# 示例使用了常规枚举和单独的字段;Rust 示例则将读取值与 Ready 变体关联起来。这样可以防止 Waiting 值意外携带可用的读取值。Rust 的 match 会返回文本,并且每个分支返回的类型都相同。穷尽匹配是编译时必须满足的要求:添加新变体后,除非通配模式已经涵盖它,否则就必须处理它。使用通配模式有时很合适,但它也会掩盖哪些变体是经过有意处理的。Rust 枚举可以直接表示不同的选项,不需要类继承层级,也不需要可空的负载字段。
完整的 C# 程序:
using System;
enum Phase { Waiting, Ready }
class Program {
static void Main() {
Phase phase = Phase.Ready;
int reading = 7;
switch (phase) {
case Phase.Ready: Console.WriteLine("reading:{0}", reading); break;
default: Console.WriteLine("waiting"); break;
}
}
}完整的 Rust 程序:
enum Phase { Waiting, Ready(i32) }
fn label(phase: Phase) -> String {
match phase {
Phase::Waiting => "waiting".to_string(),
Phase::Ready(value) => format!("reading:{}", value),
}
}
fn main() {
let _pending = Phase::Waiting;
println!("{}", label(Phase::Ready(7)));
}挑战
简单解析一条执行器命令。输入为 forward amount、back amount 或 wait;数量为 0 到 1000 的整数。要求提供公共枚举:Command,包含变体 Forward(i32)、Back(i32) 和 Wait。要求提供 API:pub fn displacement(command: Command) -> i32,对于 Forward 返回数量,对于 Back 返回数量的相反数,对于 Wait 返回零。pub fn active(command: Command) -> bool 仅在 Wait 时返回 false,即使移动数量为零也是如此。该枚举派生了 Clone, Copy,因此提供的包装代码可以将同一条命令传给这两个函数。输出 displacement active。在 actuator.rs 中实现公共 API。提供的 exercise.rs 会解析有效输入并调用该 API。返回指定文本,不要在末尾添加换行符;锁定的驱动程序会添加一个换行符。不要在 API 中打印。所有输入值都符合规定的范围。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在返回的文本末尾添加一个换行符后打印。
你的代码应写在 exercise.rs 和 actuator.rs 中。main.rs 包含提供的输入/输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod actuator;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 检查
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
assert_eq!(actuator::displacement(actuator::Command::Back(37)), -37);
assert_eq!(actuator::displacement(actuator::Command::Wait), 0);
assert!(actuator::active(actuator::Command::Forward(0)));
assert!(actuator::active(actuator::Command::Back(0)));
assert!(!actuator::active(actuator::Command::Wait));
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
// 结束公开 API 检查
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Rust中的所有课
自己练习: Rust 在线编译器