Skip to main content

Enum

Enumerations Syntax

  • The Rust Reference - Enum

  • EnumItem: fieldless, EnumItemTuple, EnumItemStruct

  • EnumDiscriminant: =, for fieldless items, default value starts from 0

  • repr attribute

Option

Match must be exhaustive. Option<T> can used directly with Some(type), None.

#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
}

enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}

fn value_in_cents(c: Coin) -> u8 {
match c {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("{:?}", state);
25
}
}
}

Option<T> enum

The Option<T> enum is so useful that it's included in the prelude.

enum Option<T> {
None,
Some(T),
}

let some_number = Some(5);
let some_char = Some('e');
let absent_number: Option<i32> = None;

Matching with Option<T>

fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}

let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);

Matching catch-all patterns

_ is a special pattern that matches any value and does not bind to that value.

let dice_roll = 9;
match dice_roll {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
other => move_player(other),
// _ => reroll(),
}

fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn move_player(num_spaces: u8) {}

if let

You can think of if let as a syntax sugar for match.

let config_max = Some(3u8);
if let Some(max) = config_max {
println!("The maximum is configured to be {}", max);
}