解构数组
你可以通过元素匹配来解构数组、元组和切片:
#[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]
来匹配切片的尾部。