If an order's status is stored as plain text, one typo ("cookng") is enough to make a status that never existed, and the compiler says nothing. The order-status board in the kitchen of Rusdi's Pancake Stall can't go wrong like that. It has just four columns: Queued, Cooking, Ready, Collected. Every ticket sits in exactly one column, never in two at once, and there is no fifth column.
In Rust, a type that works like this board is called an enum: a type whose value is always exactly one of a fixed list of choices. The choices are called variants. In code, the status board is the enum OrderStatus, each column is one variant, and the column a ticket sits in is the value of that order's status. Each variant may also carry its own data. Look at the cash drawer. A customer can pay in cash, and the cashier needs to know how much. A customer can also pay with a QR payment, by scanning a QR code, and the cashier needs the transaction code. Two ways to pay, two different kinds of data. So the status board is a plain enum, and the way to pay is an enum whose variants carry data.
Enums and variants
The code below writes the enum OrderStatus, then prints the board's note for each variant:
#[derive(Debug)]
enum OrderStatus {
Queued,
Cooking,
Ready,
Collected,
}
fn board(status: &OrderStatus) -> &str {
match status {
OrderStatus::Queued => "waiting its turn",
OrderStatus::Cooking => "on the pan",
OrderStatus::Ready => "ready to collect",
OrderStatus::Collected => "done",
}
}
fn main() {
let all = [OrderStatus::Queued, OrderStatus::Cooking, OrderStatus::Ready, OrderStatus::Collected];
for s in &all {
println!("{:?}: {}", s, board(s));
}
}
Queued: waiting its turn
Cooking: on the pan
Ready: ready to collect
Collected: done
enum OrderStatus { ... }writes the list of variants. A value of typeOrderStatusis always one of the four.- A variant is written in full with its enum's name:
OrderStatus::Cooking. JustCookingis refused:cannot find value `Cooking` in this scope. matchpicks the arm for the variant. The valueOrderStatus::Cookinggoes into theOrderStatus::Cookingarm, and the other arms are skipped.#[derive(Debug)]makes{:?}print the variant's name, as with structs.
Variants that carry data
The enum Payment below has two variants with different data. The function process uses match to read that data:
enum Payment {
Cash(u32),
Qr { code: String },
}
fn process(payment: &Payment, total: u32) {
match payment {
Payment::Cash(money) if *money < total => println!("Short by {}", total - money),
Payment::Cash(money) => println!("Cash {}, change {}", money, money - total),
Payment::Qr { code } => println!("QR {} paid", code),
}
}
fn main() {
let total = 102;
process(&Payment::Cash(110), total);
process(&Payment::Cash(100), total);
process(&Payment::Qr { code: String::from("QR-0815") }, total);
}
Cash 110, change 8
Short by 2
QR QR-0815 paid
Cash(u32)carries one unnamed number, like a tuple struct.Qr { code: String }carries a named field, like a struct. One enum can have data of a different type in each variant. This is what makes Rust's enums stronger than enums in many other languages, which are just a list of names.- In
match, the patternPayment::Cash(money)also takes the number out into the variablemoney, andPayment::Qr { code }takes out the fieldcode. if *money < totalis a guard, as in the match lesson.moneyis a borrow here (&u32), becausepaymentis a borrow too (&Payment). So*moneyreads the number. A subtraction liketotal - moneyworks without*, because Rust's-can use a borrowed number directly. A total of 102 paid with 110 in cash gives 8 in change. With 100, the guard is met, soShort by 2prints.
match must cover every variant
Now Rusdi adds a fifth variant, Cancelled, to the status enum. The board function is left unchanged: its match still has an arm for each of the four old statuses, and no _. Before you look at the result, guess: does the code compile?
error[E0004]: non-exhaustive patterns: `&OrderStatus::Cancelled` not covered
--> src/main.rs:11:11
|
11 | match status {
| ^^^^^^ pattern `&OrderStatus::Cancelled` not covered
|
note: `OrderStatus` defined here
--> src/main.rs:2:6
|
2 | enum OrderStatus {
| ^^^^^^^^^^^
...
7 | Cancelled,
| --------- not covered
It doesn't compile. Just like a match on numbers in the match lesson, a match on an enum must cover every possibility. For an enum, the possibilities are all its variants. The difference from numbers: once every variant is written, no _ is needed. So a match without _ becomes a free reminder: as soon as a new variant is added, the compiler points at every match that doesn't handle it yet. If you write _ => ..., the compiler says nothing, and a cancelled order quietly goes into the _ arm. So for your own enums, write out every variant.
Methods on enums
Enums have impl too, exactly like structs. Below, the method next moves the status one column forward on the board each time it is called:
#[derive(Debug)]
enum OrderStatus {
Queued,
Cooking,
Ready,
Collected,
}
impl OrderStatus {
fn next(self) -> OrderStatus {
match self {
OrderStatus::Queued => OrderStatus::Cooking,
OrderStatus::Cooking => OrderStatus::Ready,
OrderStatus::Ready => OrderStatus::Collected,
OrderStatus::Collected => OrderStatus::Collected,
}
}
}
fn main() {
let mut status = OrderStatus::Queued;
println!("{:?}", status);
for _ in 0..3 {
status = status.next();
println!("{:?}", status);
}
}
The output is Queued, Cooking, Ready, Collected, one per line. for _ in 0..3 runs three rounds, and the _ here means the round's number isn't used. next(self) takes the old status and hands over the new one. status = status.next(); fills status with that new status right away, so status can still be used, even though the old status was taken. A status that is already Collected stays Collected.
Option is an enum too
The Option you met in Vec and HashMap is no special feature. In the standard library, Option is just a generic enum with two variants:
enum Option<T> {
None,
Some(T),
}
So you can make Option values yourself, like the function price below. A match on an Option must be complete as well:
fn price(menu: &str) -> Option<u32> {
match menu {
"sweet pancake" => Some(32),
"egg pancake" => Some(38),
"iced tea" => Some(5),
_ => None,
}
}
fn main() {
println!("{:?}", price("iced tea"));
println!("{:?}", price("coffee"));
match price("egg pancake") {
Some(p) => println!("Price: {}", p),
None => println!("Not on the menu"),
}
}
Some(5)
None
Price: 38
Some and None can be written without Option:: because both are loaded automatically. An Option<u32> is not a u32: price("iced tea") + 2 is refused with cannot add `{integer}` to `Option<u32>` . So the value must be taken out with match first. Other ways of handling Option (and its sibling, Result) come in the Result and Option lesson.
⚠️ Variants that get forgotten, or quietly swallowed
- Leaving the enum's name off a variant. Plain
Queuedis refused withcannot find value `Queued` in this scope. WriteOrderStatus::Queued. - A new variant, an old
match. E0004non-exhaustive patterns. Add the arm in everymatchthe compiler points at. _on your own enum. The code compiles, but a new variant goes into_without anyone noticing.- Comparing with
==withoutPartialEq.status == OrderStatus::Queuedis refused:binary operation `==` cannot be applied to type `OrderStatus`. Add#[derive(PartialEq)], or usematch. - Treating an
Option<u32>like au32. Take the value out withmatchfirst.
TL;DR: enum OrderStatus { Queued, Cooking, Ready, Collected } makes a type whose value is always one variant (one choice in the enum's list), written OrderStatus::Cooking. Variants may carry data of different types, like Cash(u32) or Qr { code: String } in the enum Payment. match takes the data out through a pattern: Payment::Cash(money) puts the number in the variable money. A match on an enum must cover every variant. If you don't use _, the compiler points at every match that doesn't handle a new variant yet (E0004). Enums have impl and methods like structs. Option<T> itself is just an enum with the variants Some(T) and None, so its value (the T) is taken out with match first, not used directly.
⚡ One of a fixed list
Write:
enum OrderStatus {
Queued,
Cooking,
Ready,
Collected,
}
Meaning: enum makes a type whose value is always one of a fixed list of choices, and each choice is called a variant. A value of OrderStatus is always one of these four variants, written in full with its enum's name: OrderStatus::Cooking. Plain Cooking is refused by the compiler.
⚡ Variants that carry data
Write:
enum Payment {
Cash(u32),
Qr { code: String },
}
Meaning: Each variant may carry data of a different type: Cash carries a number (the cash amount), Qr carries the field code, which holds text (the QR payment's transaction code). That is what makes Rust's enums stronger than enums in many other languages, which are just a list of names. match takes the data out through a pattern: Payment::Cash(money) puts the number in the variable money.
⚡ A new variant, an old match
Guess first: the function board has a match with an arm for each of the four variants of OrderStatus, and no _. Then a fifth variant, Cancelled, is added, and that match is left unchanged. Does the code compile?
No. The compiler refuses with E0004 and points at the match that doesn't handle Cancelled yet.
Meaning: A match on an enum must cover every variant. For your own enums, write out every variant instead of _, so the compiler still reminds you each time a variant is added.