A match expression is made up of arms. An arm consists of a pattern to match against, and the code that should be run if the value given to match fits that armโ€™s pattern.

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}
 
fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

This seems very similar to a conditional expression used with if, but thereโ€™s a big difference: with if, the condition needs to evaluate to a Boolean value, but here it can be any type.

The code associated with each arm is an expression, and the resultant value of the expression in the matching arm is the value that gets returned for the entire match expression.

We donโ€™t typically use curly brackets if the match arm code is short. If you want to run multiple lines of code in a match arm, you must use curly brackets, and the comma following the arm is then optional.

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

match is exhaustive: the armsโ€™ patterns must cover all possibilities.

You can use catch-all patterns like this when you need the match value:

match dice_roll {
	3 => add_fancy_hat(),
	7 => remove_fancy_hat(),
	other => move_player(other),
}

Or placeholder _ like this when you want to ignore the value but want to do something:

match dice_roll {
	3 => add_fancy_hat(),
	7 => remove_fancy_hat(),
	_ => reroll(),
}

Or when we donโ€™t want to do anything with unit value ():

match dice_roll {
	3 => add_fancy_hat(),
	7 => remove_fancy_hat(),
	_ => (),
}