模式匹配
模式 Pattern
Rust中的特殊语法,用于匹配简单或复杂类型的结构
例如:与match耒表达式和其他构造结合,增强程序控制流程
模式的组成
字面值(Literals):例如数字或字符串
解构数据结构:数组、枚举、结构体、元组等
变量(Variables):命名的变量
通配符(Vildcards):_表示任意值
占位符(Placeholders):尚未具体定义的部分
使用方法
比较模式与值,若匹配成功则提取并使用数据
常用场景:例如match表达式,允许根据数据形状选择不同代码路径
Rust模式中的可反驳性 Refutability:Whether a Pattern Might Fail to Match
不可反驳模式:适用于所有可能的值,例如let x = 5 中的 x
可反驳模式:可能不匹配某些值,例如if let Some(x) = a_value 中的 Some(x)
哪些地方只能使用不可反驳的模式呢?
像函数参数、Iet语句、for循环,它们都只能使用不可反驳的模式
因为如果模式不能保证匹配成功,程序就无法继续执行下去
例如:let Some()=some_option_value; 如果值是None…程序崩溃
示例语法:
1 2 3 4 5 6 7 8 9 fn main () { let x = 1 ; match x { 1 => println! ("one" ), 2 => println! ("two" ), 3 => println! ("three" ), _ => println! ("anything" ) } }
1 2 3 4 5 6 7 8 9 10 11 fn main () { let x = Some (5 ); let y = 10 ; match x { Some (50 ) => println! ("Got 50" ), Some (y) => println! ("Matched, y = {y}" ), _ => println! ("Default case, x = {x:?}" ) } println! ("at the end: x = {x:?}, y = {y}" ); }
1 2 3 4 5 6 7 8 fn main () { let x = 1 ; match x { 1 | 2 => println! ("one or two" ), 3 => println! ("three" ), _ => println! ("anything" ) } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 fn main () { let x = 5 ; match x { 1 ..=5 => println! ("one through five" ), _ => println! ("somethong else" ) } let x = 'c' ; match x { 'a' ..='j' => println! ("early ASCII letter" ), 'k' ..='z' => println! ("late ASCII letter" ), _ => println! ("something else" ) } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 struct Point { x: i32 , y: i32 }fn main () { let p = Point { x: 0 , y:7 }; let Point { x: a, y: b } = p; assert_eq! (0 , a); assert_eq! (7 , b); let p = Point { x: 0 , y:7 }; match p { Point { x, y: 0 } => println! ("On the x axis at {x}" ), Point { x: 0 , y } => println! ("On the y axis at {y}" ), Point { x, y} => { println! ("On neither axis: ({x}, {y})" ); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 enum Message { Quit, Move { x: i32 , y: i32 }, Write (String ), ChangeColor (i32 , i32 , i32 ) }fn main () { let msg = Message::ChangeColor (0 , 160 , 255 ); match msg { Message::Quit => { println! ("Quit!" ); } Message::Move { x, y } => { println! ("Move!" ) } Message::Write (text) => { println! ("write!" ) } Message::ChangeColor (r, g, b) => { println! ("Change" ) } } }
1 let ((feet, inches), Point { x, y }) = ((3 , 10 ), Point { x: 3 , y: -10 });
以下划线开头的变量不被忽略而警告。
使用 ”..“ 可以忽略剩余的值。
向匹配项目后添加条件可以进一步筛选匹配的结果。
“@” 用于绑定,邪乎,不怎么用。