解构

解构是一种从数据结构中提取数据的方法,具体方法是编写与数据结构匹配的模式,将变量绑定到数据结构的子组件。

You can destructure tuples and arrays by matching on their elements:

元组(Tuples)

fn main() {
    describe_point((1, 0));
}

fn describe_point(point: (i32, i32)) {
    match point {
        (0, _) => println!("on Y axis"),
        (_, 0) => println!("on X axis"),
        (x, _) if x < 0 => println!("left of Y axis"),
        (_, y) if y < 0 => println!("below X axis"),
        _ => println!("first quadrant"),
    }
}

数组(Arrays)

#[rustfmt::skip]
fn main() {
    let triple = [0, -2, 3];
    println!("Tell me about {triple:?}");
    match triple {
        [0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
        [1, ..]   => println!("First is 1 and the rest were ignored"),
        _         => println!("All elements were ignored"),
    }
}
This slide should take about 5 minutes.
  • Create a new array pattern using _ to represent an element.
  • 向数组中添加更多的值。
  • 指出 .. 是如何扩展以适应不同数量的元素的。
  • 展示使用模式 [.., b][a@..,b] 来匹配切片的尾部。