-
StackOverflow 文档
-
Rust 教程
-
选项
-
解构期权
fn main() {
let maybe_cake = Some("Chocolate cake");
let not_cake = None;
// The unwrap method retrieves the value from the Option
// and panics if the value is None
println!("{}", maybe_cake.unwrap());
// The expect method works much like the unwrap method,
// but panics with a custom, user provided message.
println!("{}", not_cake.expect("The cake is a lie."));
// The unwrap_or method can be used to provide a default value in case
// the value contained within the option is None. This example would
// print "Cheesecake".
println!("{}", not_cake.unwrap_or("Cheesecake"));
// The unwrap_or_else method works like the unwrap_or method,
// but allows us to provide a function which will return the
// fallback value. This example would print "Pumpkin Cake".
println!("{}", not_cake.unwrap_or_else(|| { "Pumpkin Cake" }));
// A match statement can be used to safely handle the possibility of none.
match maybe_cake {
Some(cake) => println!("{} was consumed.", cake),
None => println!("There was no cake.")
}
// The if let statement can also be used to destructure an Option.
if let Some(cake) = maybe_cake {
println!("{} was consumed.", cake);
}
}