← 中文资源

简体中文版本

let 中的嵌套解构模式

用解构模式一次取出结构体与元组的字段:嵌套 match 同时拆出首段元组与剩余切片,let 解构元组时用 .. 忽略尾部元素。

阅读英文原文

实现说明

let 中的嵌套解构模式可以归结为函数 summarize、main。 本示例的循环部分是 for s in [&a, &b, &c]。这里的控制流就是 match:分支穷尽地列出值的形态。

使用要点

  • 直接运行文件,输出会带上标签,比如 first of tuple:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 summarize。

常见问题

运行「let 中的嵌套解构模式」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 first of tuple: 标签标明各步骤。

入口签名:fn summarize(Shipment { id, legs }: &Shipment) -> String

核心语句

Some((first, rest)) if !rest.is_empty() => {
    let (city, _) = first;
    format!("shipment {id}: via {city} plus {} more legs", rest.len())
}
Some((first, _)) => {
    let (city, _) = first;
    format!("shipment {id}: single leg to {city}")
}

代码示例

struct Shipment {
    id: u32,
    legs: Vec<(String, u32)>,
}

// 参数位置直接用结构体模式解构(destructuring)
fn summarize(Shipment { id, legs }: &Shipment) -> String {
    match legs.split_first() {
        Some((first, rest)) if !rest.is_empty() => {
            let (city, _) = first;
            format!("shipment {id}: via {city} plus {} more legs", rest.len())
        }
        Some((first, _)) => {
            let (city, _) = first;
            format!("shipment {id}: single leg to {city}")
        }
        None => format!("shipment {id}: no legs"),
    }
}

fn main() {
    let a = Shipment { id: 7, legs: vec![("rot".into(), 10), ("ams".into(), 5)] };
    let b = Shipment { id: 8, legs: vec![("ham".into(), 3)] };
    let c = Shipment { id: 9, legs: vec![] };
    for s in [&a, &b, &c] {
        println!("{}", summarize(s));
    }
    // let 解构元组:其余用 .. 忽略
    let (first, ..) = (1, 2, 3, 4);
    println!("first of tuple: {first}");
}