頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
github地址:https://github.com/anonymousGiga/learn_rus...
1、匹配字面值
例子:
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
2、匹配命名變數
例子:
fn main() {
let x = Some(5);
let y = 10; //1處
match x {
Some(50) => println!("Got 50"),
Some(y) => println!("Matched, y = {:?}", y), //此處的y和上面1處的y不一樣,此處是引入的變數y覆蓋之前的y
_ => println!("Default case, x = {:?}", x),
}
println!("at the end: x = {:?}, y = {:?}", x, y);
}
3、多個模式
例子:
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
說明: |表示或,即匹配1或者2
本作品採用《CC 協議》,轉載必須註明作者和本文連結