rust match 模式匹配摘录
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使用者。关说不练假把式,模式匹配有挺多知识点的,本文将知识点摘录到一个例子中,方便后续查阅。

 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号