← 中文资源

简体中文版本

枚举方法 match self 变体

在 impl 块里为枚举写方法并 match self:&self 做只读判断,matches! 压缩布尔测试,消耗 self 的方法把状态机推进到下一态。

阅读英文原文

实现说明

枚举方法 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());
}