实现说明
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}");
}