枚举与模式匹配
枚举
定义枚举
枚举值
将数据附加到枚举的变体中
标准库中的IpAddr
案例
Option枚举
Rust没有Null
Rust中类似null的概念
Option
比Null好在哪里?
控制流运算符match
强大的控制流运算符match
案例
#[derive(Debug)]
enum UsState{
Alabama,
Alaska,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState)
}
fn value_in_us_cents(coin:Coin)-> u8{
match coin{
Coin::Penny=>{
println!("Penny");
1
}
Coin::Nickel=>5,
Coin::Dime=>10,
Coin::Quarter(state)=>{
println!("State quarter from {:?}!",state);
25
}
}
}
fn main() {
let c =Coin::Quarter(UsState::Alabama);
println!("{}",value_in_us_cents(c));
println!("Hello, world!");
}
匹配Option
fn main() {
let five =Some(5);
let sex =plus_one(five);
let none =plus_one(None);
}
fn plus_one (x:Option<T>)->Option<i32>{
match x {
None =>None,
Some(i)=>Some(i+1),
}
}
if let
fn main() {
let v =Some(0u8);
match v {
Some(3)=>println!("3"),
// Some(4)=>println!("4"),
// Some(5)=>println!("5"),
// Some(6)=>println!("6"),
_=>(),
}
if let Some(3) = v {println!("3");}
}
fn main() {
let v =Some(0u8);
match v {
Some(3)=>println!("3"),
// Some(4)=>println!("4"),
// Some(5)=>println!("5"),
// Some(6)=>println!("6"),
_=>(),
}
if let Some(3) = v {
println!("3");
}else{
println!("other");
}
}