Bitpath

Lesson 2 · Unit 02

Pattern matching

Cover every case, and take values apart by shape

13 exercisesabout 3 min

What you practise

  • match must cover every case, destructuring, Option instead of null, if let and let else

Try a question from this lesson

Pick one

This match forgot one of the three lights. Python would find out at run time. What does Rust do?

Rust
enum Light { Red, Amber, Green }
fn go(l: Light) -> bool {
    match l {
        Light::Red => false,
        Light::Green => true,
    }
}

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

match covers every case

match compares a value against patterns from top to bottom and runs the first arm that fits. It is an expression: every arm must produce the same type.

| joins alternatives and _ matches anything. With _ as the last arm the match is always complete, but the compiler can no longer tell you about a case you forgot.

Rust
let n = 3;
let name = match n {
    1 => "one",
    2 | 3 => "few",
    _ => "many",
};
println!("{name}");

Concept

Option instead of null

In Python any variable might be None, and you find out when it crashes. Rust has no null.

A value that may be missing has the type Option<T>, an enum with two variants: Some(value) or None. An Option<i32> is not an i32. You must take it apart before using the number, so the missing case cannot be forgotten.

Rust
let v = vec![10, 20];
let a = v.get(1);
let b = v.get(5);
println!("{:?} {:?}", a, b);

10 more exercises in the app

  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy