模式可能出现的位置

match分支

一个模式最常用的位置就是match表达式的分支。 match表达式有match关键字、用于匹配的值和一个或多个分支构成。而分支包含一个模式和值匹配分支的模式时运行的表达式。

match VALUE {
	PATTERN => EXPRESSION,
	PATTERN => EXPRESSION,
	PATTERN => EXPRESSION,
}

match表达式必须穷尽。可以使用_匹配所有的模式。

if let条件表达式

这个match表达式的简写,表示只关系match表达式中的一个分支。还可以组合使用else if, else if. else if let。

fn main() {
    let favorite_color: Option<&str> = None;
    let is_tuesday = false;
    let age: Result<u8, _> = "34".parse();
 
    if let Some(color) = favorite_color {
        println!("Using your favorite color, {}, as the background", color);
    } else if is_tuesday {
        println!("Tuesday is green day!");
    } else if let Ok(age) = age {
        if age > 30 {
            println!("Using purple as the background color");
        } else {
            println!("Using orange as the background color");
        }
    } else {
        println!("Using blue as the background color");
    }
}
 

while let

与if let类似,只要模式匹配就一直进行循环。

fn main() {
    let mut stack = Vec::new();
 
    stack.push(1);
    stack.push(2);
    stack.push(3);
 
    while let Some(top) = stack.pop() {
        println!("{}", top);
    }
}
 

for循环

for循环中也是有模式的,通常直接用来结构迭代元素。

fn main() {
    let v = vec!['a', 'b', 'c'];
 
    for (index, value) in v.iter().enumerate() {
        println!("{} is at index {}", value, index);
    }
}

let语句

这是一个声明变量的关键字,但是也可以直接结构出新的变量。

fn main() {
    let (x, y, z) = (1, 2, 3);
}
 

函数参数

在形参中可以进行结构,以便使用传入的参数的内容。例如传入的元组就经常进行结构

fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}
 
fn main() {
    let point = (3, 5);
    print_coordinates(&point);
}
 

闭包类似于函数,也可以在闭包参数列表中使用模式。

Refutability(可反驳性): 模式是否会匹配失效

模式有两种形式:

  • refutable(可反驳的)。对某些可能的值进行匹配会失败的模式为可反驳的。例如if let Some(x) = a_value,这个模式匹配可能会失败。
  • irrefutable(不可反驳的)。能匹配任何传递的可能值的模式。例如let x = 5不可能失败。

let和for只能接收不可反驳的模式。if let和while let只能接受可反驳的模式。