Pattern Matching in Rust During Variable Assignment
Rust
The match
keyword in Rust is something like a C switch
statement - but it can also be used during variable assignment:
fn main() {
// Match is an expression as well as a statement. This example shows how
// a variable is set based on an Option enum.
// ------------------------------------------
let msg_option = Some("+++MELON MELON MELON+++"); // Some variant
let msg_option_empty = None; // None variant
// The variable msg is assigned a value dependent upon the Option variant
let msg = match msg_option {
Some(m) => m, // m is the unwrapped data from the option
None => "Out of Cheese Error",
};
println!("msg = {}", msg);
// As above, but handling the None variant
let msg_2 = match msg_option_empty {
Some(m) => m, // In this case we won't enter this branch
None => "Out of Cheese Error", // msg_2 set to this value
};
println!("msg_2 = {}", msg_2);
}
// Output:
// msg = +++MELON MELON MELON+++
// msg_2 = Out of Cheese Error
This is a really handy idiom given that functions in Rust often return an Option
enum.
You could achieve the same thing using unwrap_or()
:
fn main() {
let msg_option = Some("+++MELON MELON MELON+++"); // Some variant
let msg_option_empty = None; // None variant
let default_msg = "+++Please Reinstall Universe and Reboot+++";
let msg = msg_option.unwrap_or(default_msg);
println!("msg = {}", msg);
// As above, but handling the None variant
let msg_2 = msg_option_empty.unwrap_or(default_msg);
println!("msg_2 = {}", msg_2);
}
// Output:
// msg = +++MELON MELON MELON+++
// msg_2 = +++Please Reinstall Universe and Reboot+++
comments powered by Disqus