Beginner Fundamentals

Enums

An enum defines a type by listing its possible variants. A value of the enum is exactly one of those variants at a time.

Defining an enum

enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let heading = Direction::North;
    move_player(heading);
}

fn move_player(d: Direction) {
    // ...
}

match

The match expression compares a value against patterns and runs the matching branch. It must cover every variant.

fn name_of(d: Direction) -> &'static str {
    match d {
        Direction::North => "north",
        Direction::South => "south",
        Direction::East => "east",
        Direction::West => "west",
    }
}

Option

Rust has no null. Instead, the built-in Option enum represents a value that may be present (Some) or absent (None).

fn main() {
    let maybe_age: Option<u32> = Some(30);
    let nothing: Option<u32> = None;

    match maybe_age {
        Some(age) => println!("Age is {}", age),
        None => println!("No age given"),
    }
}

Using Option forces you to handle the missing case, eliminating an entire class of null-related bugs.