6.1. Defining an Enum

Rust has rich enum support that can associate enum variants with some structured or scalar data, for example:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

This enum has four variants with different types:

6.2. The match Control Flow Construct

With match , we can use it like switch in many languages like C/C++, but match in Rust can match with many more complicated data types like enums. match will stop once any arm matches.

Note that one needs to exhaust all possile arms to compile, so we can have a default arm like other below.

match dice_roll {
    3 => add_fancy_hat(),
    7 => {
				// do sth
		},
    other => reroll(other),
}

One can also use _ => () to replace the other arm if we don't need to do anything.

6.3. Concise Control Flow with if let

    let mut count = 0;
    if let Some(state) = resp { // Some(state) works as a match arm
        println!("State is {:?}!", state);
    } else {
        count += 1;
    }

If you have a situation in which your program has logic that is too verbose to express using a match, remember that if let is in your Rust toolbox as well.