Enum Methods Match Self Variants
Implement methods on enums and match on self: &self predicates read variants, matches! compresses boolean tests, and consuming self advances state.
Code
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());
}Inside the snippet
The code’s whole job belongs to the functions is_finished, describe, advance and main.
A match spells out every case; omit one and the code does not compile.
Watch out for
- Nothing needs adding to the project before it runs.
Using it
Signature: fn is_finished(&self) -> bool
Output lines are prefixed (finished=), so the effect of each step stands out plainly.
There are 3 calls inside main — describe, advance and is_finished — executed top to bottom.
Key statements
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,
}
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Enum Methods Match Self Variants print when run?
- The script runs standalone; its 1 labeled outputs include `finished=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.