A match expression is made up of arms. An arm consists of a pattern to
match against, and the code that should be run if the value given to match
fits that arm's pattern in turn.
let secret_number = rand::thread_rng().gen_range(1..=100);
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
Bind by reference with ref keyword
At first it seems a bit crazy that there's a keyword for this, but it's because
using &Foo is a different type from Foo. So you need to use ref Foo if
you want to match against Foo not Foo, but use a reference to actually
unpack the value in your match arm.
let maybe_name = Some(String::from("Alice"));
// Using `ref`, the value is borrowed, not moved ...
match maybe_name {
Some(ref n) => println!("Hello, {n}"),
_ => println!("Hello, world"),
}
// ... so it's available here!
println!("Hello again, {}", maybe_name.unwrap_or("world".into()));