Rust Pattern matching with bindings


Example

It is possible to bind values to names using @:


struct Badger {
    pub age: u8
}

fn main() {
    // Let's create a Badger instances
    let badger_john = Badger { age: 8 };

    // Now try to find out what John's favourite activity is, based on his age
    match badger_john.age {
        // we can bind value ranges to variables and use them in the matched branches
        baby_age @ 0...1 => println!("John is {} years old, he sleeps a lot", baby_age),
        young_age @ 2...4 => println!("John is {} years old, he plays all day", young_age),
        adult_age @ 5...10 => println!("John is {} years old, he eats honey most of the time", adult_age),
        old_age => println!("John is {} years old, he mostly reads newspapers", old_age),
    }
}

This will print:

John is 8 years old, he eats honey most of the time