Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Match

When you have to choose between many possibilities, a long chain of else if gets tiring to read. Rust has a beautiful tool for this: match. You give it a value, list the possible patterns, and Rust runs the code of the first pattern that fits. Think of a sorting machine at a post office that sends each letter down the right chute.

fn main() {
    let day = 3;
    match day {
        1 => println!("Monday"),
        2 => println!("Tuesday"),
        3 => println!("Wednesday"),
        4 => println!("Thursday"),
        5 => println!("Friday"),
        _ => println!("Weekend!"),
    }
}
Output
Wednesday

Each line inside is called an arm. On the left of the arrow => is a pattern; on the right is what to do. The last pattern, a single underscore _, means "anything else". It catches every value that did not match an earlier arm.

Every case must be handled

Here is what makes match special: Rust checks that you have covered every possible value. If you delete the _ arm above, the program does not compile, because day could be 6, or 100, and you have not said what should happen then. This check is called exhaustiveness, and it is one of the ways Rust stops bugs before they start. When we meet enums later, you will see how powerful it is.

Several values and ranges

One arm can match several values joined with |, which you can read as "or". It can also match a whole range of numbers with ..=:

fn main() {
    let marks = 82;
    match marks {
        90..=100 => println!("Grade A"),
        75..=89 => println!("Grade B"),
        60..=74 => println!("Grade C"),
        0..=59 => println!("Keep going, you will get there"),
        _ => println!("That is not a valid mark"),
    }

    let letter = 'e';
    match letter {
        'a' | 'e' | 'i' | 'o' | 'u' => println!("{} is a vowel", letter),
        _ => println!("{} is a consonant", letter),
    }
}
Output
Grade B
e is a vowel

match gives a value

Like if, a match is an expression, so it can produce a value directly. All arms must give the same type:

fn main() {
    let month = 2;
    let days = match month {
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    };
    println!("Month {} has {} days", month, days);
}
Output
Month 2 has 28 days

When an arm needs more than one line, put its code in curly brackets: 3 => { println!("..."); println!("..."); }.

Practice exercises

  1. Write a match that turns the numbers 1 to 7 into day names, with a message for anything else.
  2. Use ranges to describe a temperature as cold, mild, warm or hot.
  3. Remove the _ arm from a match on a number and read the compiler's explanation.