← 中文资源

简体中文版本

split_first 的头尾遍历

split_first 借走头部并返回余下切片:while let 逐段走完序列,不拷贝、不做下标算术,空切片返回 None。

阅读英文原文

实现说明

split_first 的头尾遍历以函数 main为骨架。 迭代发生在 while let Some((head, rest)) = remaining.split_first() 内部——循环之外的语句只执行一遍。分支逻辑走 match,穷尽性检查把漏掉的分支变成编译错误。

使用要点

  • 每一步打印都带着自己的标签:first:、empty path、total:。

常见问题

运行「split_first 的头尾遍历」会打印什么?

运行文件本身,first:、empty path、total: 这些前缀各对应一段演示逻辑。

核心语句

while let Some((head, rest)) = remaining.split_first() {
    total += head;
    remaining = rest;
}
match hops.split_first() {
    Some((first, rest)) => println!("first: {first}, rest: {rest:?}"),
    None => println!("empty path"),
}

代码示例

fn main() {
    let hops = [3, 9, 4, 12];

    // split_first 借走头部并返回余下切片:不拷贝、不做下标算术
    match hops.split_first() {
        Some((first, rest)) => println!("first: {first}, rest: {rest:?}"),
        None => println!("empty path"),
    }

    // while let 逐段走完整个序列(head/tail walk)
    let mut remaining: &[u32] = &hops;
    let mut total = 0;
    while let Some((head, rest)) = remaining.split_first() {
        total += head;
        remaining = rest;
    }
    println!("total: {total}");

    let empty: [u32; 0] = [];
    assert!(empty.split_first().is_none());
    println!("empty slice yields None");
}