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 {
...
// Create a boolean value
let a = true;
// The following expression will try and find a pattern for our value starting with
// the topmost pattern.
// This is an exhaustive match expression because it checks for every possible value
match a {
true => println!("a is true"),
...
It's possible to treat multiple, distinct values the same way, using |:
enum Colour {
Red,
Green,
Blue,
Cyan,
Magenta,
Yellow,
Black
}
enum ColourModel {
RGB,
CMYK
}
// let's take an example colour
let colour = Colour::Red;
let model = match ...
Patterns can be matched based on values independent to the value being matched using if guards:
// Let's imagine a simplistic web app with the following pages:
enum Page {
Login,
Logout,
About,
Admin
}
// We are authenticated
let is_authenticated = true;
// But we aren't admins...
if let
Combines a pattern match and an if statement, and allows for brief non-exhaustive matches to be performed.
if let Some(x) = option {
do_something(x);
}
This is equivalent to:
match option {
Some(x) => do_something(x),
_ => {},
}
These blocks can also have e...
Sometimes it's necessary to be able to extract values from an object using only references (ie. without transferring ownership).
struct Token {
pub id: u32
}
struct User {
pub token: Option<Token>
}
fn main() {
// Create a user with an arbitrary token
let user = User...