🎓 A1Learner
🔍

Rust Match

match is a Rust control tool that compares one value against a list of patterns. match must cover every possible value.

A long else if chain does the job

An else if chain can test many values. Each new case adds another branch:

fn main() {
    let code = 404;
    let msg = if code == 200 {
        "OK"
    } else if code == 404 {
        "Not Found"
    } else if code >= 500 && code <= 599 {
        "Server error"
    } else {
        "Other"
    };
    println!("{}", msg);
}

Match tries arms in order

Each line is an arm: a pattern, =>, then the value or code for it. Arms are tried in order, and the first matching arm runs. The value of the whole match can be saved:

let n = 2;
let word = match n {
    1 => "one",
    2 => "two",
    _ => "many",
};
println!("{}", word);

Or patterns share an arm

One arm can cover several values. Write the choices with | between them:

let grade = 'B';
let word = match grade {
    'A' | 'B' => "pass",
    _ => "not yet",
};
println!("{}", word);

An arm can run a block

Use { } around an arm to run several lines. The last value in the block is the value of the arm. The comma after a block arm is optional:

let n = 3;
let label = match n {
    1 => "one",
    _ => {
        let extra = "not one";
        extra
    }
};
println!("{}", label);

A catch-all can keep the value

Name the catch-all and it binds every leftover value, ready to use. Write _ instead when you do not need the value, and _ => () when the right action is to do nothing:

let n = 9;
match n {
    0 => println!("zero"),
    other => println!("something else: {}", other),
}

Example

fn main() {
    let code = 404;
    let msg = match code {
        200 => "OK",
        404 => "Not Found",
        500 => "Server error",
        _ => "Other",
    };
    println!("{}", msg);
}

Key points

  • A pattern can bind the data inside a variant.
  • Coin::Quarter(state) matches a quarter.
  • It saves the value inside it in the name state.
  • The arm can then use it
  • Put the catch-all last.
  • Arms are tried in order.
  • Any arm after a catch-all can never run.
  • Rust warns you about it

In this example, code is 404. match tests it against each arm in order. It is not 200. It is 404, so the second arm matches and gives the text "Not Found". That value is saved in msg and printed. The 500 arm would catch a server error code. The final _ arm catches everything else, which is how match knows every case is covered.

Note

Unlike switch in many languages, match must cover every possible value.

If a case is missing, the code will not compile.

Nothing can fall through by accident.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does "exhaustive" mean for a match?