Enums and match
Programming Languages · Rust Data · 12 min
List the possible choices with enum, handle each one with match, and deal with missing values using Option.
An enum lists the choices
An enum is a type with a fixed list of choices, called variants. A value of that type is always exactly one of them:
enum Direction {
North,
South,
}
let way = Direction::North;
Note the :: between the enum name and the variant.
Above
main, defineenum Lightwith the variantsRed,YellowandGreen.In
main, createnowholdingLight::Green.
match picks a branch
match looks at a value and runs the arm that fits. Each arm is pattern => code:
match way {
Direction::North => println!("Up"),
Direction::South => println!("Down"),
}
Rust checks you've covered every variant. Forget one and it won't compile. That's a nice safety net.
Use
matchonnow: printStopforRed,Slow downforYellowandGoforGreen.
match on numbers, and _
match works on numbers too. The pattern _ means "anything else", so you don't have to list every number.
Like if, match can give back a value:
let word = match n {
1 => "one",
2 => "two",
_ => "many",
};
Create
namewith amatchonday:6 => "Saturday",7 => "Sunday", and_ => "a weekday".Print
Day 6 is Saturdayusingdayandname.
Option: Some or None
Rust has no null. A value that might be missing is an Option, a built-in enum with two variants: Some(value) or None. You match it to get the value out safely:
match maybe {
Some(n) => println!("Got {}", n),
None => println!("Nothing"),
}
Some(n) gives the value inside the name n.
Write
fn describe(x: Option<u32>)that matchesx:Some(n)printsFoundandn,NoneprintsNothing here.Call
describewitha,bandc, in that order.
if let for one case
When you only care about one pattern, if let is a shorter match:
if let Some(n) = maybe {
println!("Got {}", n);
} else {
println!("Nothing");
}
The else part is optional.
Use
if let Some(n) = nicknameto printHi, Ace!usingn.Do the same for
other, with anelsethat printsHi there!
Put it together: a coin counter
Turn each coin into its value in cents with match, then use if let to cash in a bonus coin that might not be there.
Write
fn value(coin: Coin) -> u32that usesmatchto give 1, 5, 10 or 25 cents.In
main, printvalue(Coin::Dime) + value(Coin::Quarter)as35 cents.Use
if let Some(c) = bonusto printBonus: 5 centswithvalue(c).
More in Rust Data
Previous: Structs · Next: Vectors and Strings