Rust has rich enum support that can associate enum variants with some structured or scalar data, for example:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
This enum has four variants with different types:
Quit
has no data associated with it at all.Move
has named fields like a struct does.Write
includes a single String
.ChangeColor
includes three i32
values.With match
, we can use it like switch
in many languages like C/C++, but match
in Rust can match with many more complicated data types like enums. match
will stop once any arm matches.
Note that one needs to exhaust all possile arms to compile, so we can have a default arm like other
below.
match dice_roll {
3 => add_fancy_hat(),
7 => {
// do sth
},
other => reroll(other),
}
One can also use _ => ()
to replace the other
arm if we don't need to do anything.
let mut count = 0;
if let Some(state) = resp { // Some(state) works as a match arm
println!("State is {:?}!", state);
} else {
count += 1;
}
If you have a situation in which your program has logic that is too verbose to express using a match
, remember that if let
is in your Rust toolbox as well.