实现说明
枚举方法 match self 变体的核心是函数 is_finished、describe、advance、main。
match 表达式是穷尽的——编译器强制没有遗漏的分支。
使用要点
- 直接运行文件,输出会带上标签,比如
finished=——输出的每一行都能指回产生它的那次调用。 - 运行整个文件:
main会依次驱动describe、advance、is_finished。
常见问题
运行「枚举方法 match self 变体」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 finished= 标签标明各步骤。
主要签名是 fn is_finished(&self) -> bool
核心语句
fn is_finished(&self) -> bool {
matches!(self, Job::Failed { .. } | Job::Done)
}
fn describe(&self) -> String {
match self {
Job::Queued { attempts } => format!("queued (try {attempts})"),
Job::Running => String::from("running"),
Job::Failed { reason } => format!("failed: {reason}"),
Job::Done => String::from("done"),
}
}
fn advance(self) -> Self {
match self {
Job::Queued { .. } => Job::Running,
Job::Running => Job::Done,
finished @ (Job::Failed { .. } | Job::Done) => finished,
}
}
代码示例
enum Job {
Queued { attempts: u8 },
Running,
Failed { reason: String },
Done,
}
impl Job {
// methods on the enum: &self reads variants, consuming self moves state
fn is_finished(&self) -> bool {
matches!(self, Job::Failed { .. } | Job::Done)
}
fn describe(&self) -> String {
match self {
Job::Queued { attempts } => format!("queued (try {attempts})"),
Job::Running => String::from("running"),
Job::Failed { reason } => format!("failed: {reason}"),
Job::Done => String::from("done"),
}
}
// consuming self: the state machine moves into its next state
fn advance(self) -> Self {
match self {
Job::Queued { .. } => Job::Running,
Job::Running => Job::Done,
finished @ (Job::Failed { .. } | Job::Done) => finished,
}
}
}
fn main() {
let mut job = Job::Queued { attempts: 2 };
println!("{}", job.describe());
job = job.advance();
println!("{}", job.describe());
job = job.advance();
println!("{} finished={}", job.describe(), job.is_finished());
let failed = Job::Failed { reason: "oom".into() };
println!("{}", failed.describe());
println!("finished={}", failed.is_finished());
}