rust match 模式匹配摘錄
阿新 • • 發佈:2022-02-07
Rust中的模式匹配
模式匹配大概有以下幾種:
- let語句
- if let語句
- match表示式
- 函式簽名
- for迴圈
- while let語句
// 1 let語句 let x = 1; let option_x = Some(x); // 2 if let if let Some(num) = option_x { println!("num is : {}", num) } // 3 match表示式 match x { 1..=10 => println!("num is in range [1, 10]"), _ => println!("num out of range!"), } // 4 函式簽名 fn myfun(x: i32) { println!("x is : {}", x) } myfun(x); // 5 for 迴圈 for x in 1..10 { println!("num in loop is : {}", x) } // 6 while let let mut nums = vec![1,2,3]; while let Some(num) = nums.pop() { println!("num in while let is : {}", num) }
注意while let語句不能寫成
while let Some(num) = &mut vec![1, 2, 3].pop() {
println!("num in while let is : {}", num)
}
每次相當於新生成一個vec。
match表示式
- 可以使用豎線 | 並列多個選項
- 範圍模式。可以使用 ..= 列出一個範圍,比如
1..=10
代表範圍[1, 10]。目前不支援 .. 比如1..10
,代表範圍[1,10),不包括10。for迴圈支援 - 通過@來繫結變數。
- 匹配守衛新增額外條件。額外條件可以使用外部變數y,而避免覆蓋外部變數。匹配守衛也可以與 | 組合使用
- 通過 _ 來忽略值,一般做最後的兜底使用
範圍模式僅支援char和數值
fn main() { let x = 60; let y = false; match x { 10 | 11 => println!("x is 10, 11"), 1..=9 => println!("x is in range [1, 9]"), id @ 12..=20 => println!("x in range [12, 20], id is {}", id), n if !y => println!("y is false, x is: {}", n), _ => println!("nothing match"), } }
總結
模式匹配是rust語言的重要組成部分,只有掌握了才是地道的rust使用者。關說不練假把式,模式匹配有挺多知識點的,本文將知識點摘錄到一個例子中,方便後續查閱。