03.01 Rust 編程視頻教程(進階)——024

視頻地址

頭條地址:https://www.ixigua.com/i6775861706447913485

源碼地址

github地址:見擴展鏈接。

講解內容

1、匹配守衛提供的額外的條件匹配守衛是一個指定於match分支模式之後的額外的if條件,它必須滿足才能選擇此分支。例子1:

<code>let num = Some(4);match num {    Some(x) if x < 5 => println!("less than five: {}", x),   //匹配守衛    Some(x) => println!("{}", x),    None => (),}/<code>

例子2:

<code>fn main() {    let x = Some(5);    let y = 10;    //位置1    match x {        Some(50) => println!("Got 50"),        Some(n) if n == y => println!("Matched, n = {}", n),  //此處的y就是位置1處的y,不是額外創建的變量        _ => println!("Default case, x = {:?}", x),    }    println!("at the end: x = {:?}, y = {}", x, y);}/<code>

例子3:

<code>let x = 4;let y = false;match x {    4 | 5 | 6 if y => println!("yes"), //等價於(4 | 5 | 6) if y => println!("yes"),    _ => println!("no"),}/<code>

2、綁定@運算符允許我們在創建一個存放值的變量,並且測試這個變量的值是否匹配模式。例子:

<code>enum Message {    Hello { id: i32 },}let msg = Message::Hello { id: 5 };match msg {    Message::Hello { id: id_variable @ 3..=7 } => {  //創建id_variable 存放id的值,同時測試值是否在3到7的範圍        println!("Found an id in range: {}", id_variable)    },    Message::Hello { id: 10..=12 } => {        println!("Found an id in another range")    },    Message::Hello { id } => {        println!("Found some other id: {}", id)    },}/<code>

3、作業:自己編寫一個使用@綁定並且測試值的例子。


分享到:


相關文章: