rust-枚举和模式匹配「rustwiki.org」
看看代码,熟悉语法,概念和其他语言基本一致。
枚举定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), }
struct QuitMessage; struct MoveMessage { x: i32, y: i32, } struct WriteMessage(String); struct ChangeColorMessage(i32, i32, i32);
impl Message { fn call(&self) { } }
|
match匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| enum Coin { Penny, Nickel, Dime, Quarter, }
fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } }
fn main() {}
|
Option
1 2 3 4
| enum Option<T> { Some(T), None, }
|
match Option
1 2 3 4 5 6 7 8 9 10
| fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } }
let five = Some(5); let six = plus_one(five); let none = plus_one(None);
|
if let 简化match
类似java streamapi中 ifPresent
1 2 3
| if let Some(3) = some_u8_value { println!("three"); }
|
加上else
1 2 3 4 5 6
| let mut count = 0; if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; }
|