解構陣列

您可以在陣列、元組和切片的元素上配對,藉此解構陣列、元組和切片:

#[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"),
    }
}
  • 您可以解構未知長度的切片,同樣的方法也適用於固定長度的模式。

    fn main() {
        inspect(&[0, -2, 3]);
        inspect(&[0, -2, 3, 4]);
    }
    
    #[rustfmt::skip]
    fn inspect(slice: &[i32]) {
        println!("Tell me about {slice:?}");
        match slice {
            &[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"),
        }
    }
  • 建立使用 _ 來代表元素的新模式。

  • 在陣列中加入更多值。

  • 向學員指出為了因應不同元素數量的情況,.. 會如何展開。

  • 向學員說明與模式 ([.., b][a@..,b]) 末端的配對情形。