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, define enum Light with the variants Red, Yellow and Green.

  • In main, create now holding Light::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 match on now: print Stop for Red, Slow down for Yellow and Go for Green.

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 name with a match on day: 6 => "Saturday", 7 => "Sunday", and _ => "a weekday".

  • Print Day 6 is Saturday using day and name.

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 matches x: Some(n) prints Found and n, None prints Nothing here.

  • Call describe with a, b and c, 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) = nickname to print Hi, Ace! using n.

  • Do the same for other, with an else that prints Hi 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) -> u32 that uses match to give 1, 5, 10 or 25 cents.

  • In main, print value(Coin::Dime) + value(Coin::Quarter) as 35 cents.

  • Use if let Some(c) = bonus to print Bonus: 5 cents with value(c).

More in Rust Data

Previous: Structs · Next: Vectors and Strings