← 中文资源

简体中文版本

切片模式的数组解构

match 的切片模式声明精确形状:固定长度模式断言元素个数,head 配 rest @ .. 把剩余元素绑定为子切片。

阅读英文原文

实现说明

功能面由函数 describe、main构成。 match 表达式是穷尽的——编译器强制没有遗漏的分支。

使用要点

  • 演示输出是带标签的(first two:),每个操作都会留下自己的一行标注。
  • main 按顺序串起 describe;运行文件就会把这个流程跑一遍。

常见问题

运行「切片模式的数组解构」会打印什么?

整个文件跑完,输出行以 first two: 这类前缀开头。

入口签名:fn describe(readings: &[i32]) -> String

核心语句

match readings {
    [] => "empty".to_string(),
    // 固定长度模式:只匹配恰好一个 / 两个元素的切片
    [only] => format!("single: {only}"),
    [first, second] => format!("pair: {first} vs {second}"),
    // head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
    [head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.len()),
}

代码示例

fn describe(readings: &[i32]) -> String {
    match readings {
        [] => "empty".to_string(),
        // 固定长度模式:只匹配恰好一个 / 两个元素的切片
        [only] => format!("single: {only}"),
        [first, second] => format!("pair: {first} vs {second}"),
        // head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
        [head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.len()),
    }
}

fn main() {
    let data = [7, 11, 13, 17];
    println!("{}", describe(&data));
    println!("{}", describe(&data[..2]));
    println!("{}", describe(&data[..1]));
    println!("{}", describe(&[]));

    // let 解构固定长度数组:.. 吞掉剩余元素
    let [a, b, ..] = data;
    println!("first two: {a} {b}");
}