← 中文资源

简体中文版本

迭代器 advance_by 与 nth 按位跳过

advance_by 与 nth(n) 按位置前进迭代器:被跳过的元素直接消费、不落任何集合;越过末尾时分别返回 Err 与 None。nth(0) 等价于 next()。

阅读英文原文

实现说明

迭代器 advance_by 与 nth 按位跳过可以归结为函数 main。 match 表达式是穷尽的——编译器强制没有遗漏的分支。

使用要点

  • 跑完文件,输出里会留下标记——after advance_by(2):、nth(3):、then next():。

常见问题

运行「迭代器 advance_by 与 nth 按位跳过」会打印什么?

整个文件跑完,输出行以 after advance_by(2):、nth(3):、then next(): 这类前缀开头。

核心语句

let shortfall = match exhausted.advance_by(10) {
    Ok(()) => 0,
    Err(k) => k.get(),
};
let mut exhausted = letters.iter();
let mut skip_two = letters.iter();

代码示例

fn main() {
    let letters = ['a', 'b', 'c', 'd', 'e', 'f'];

    // Iterator::advance_by skips positions without binding the skipped items
    let mut skip_two = letters.iter();
    skip_two.advance_by(2).unwrap();
    println!("after advance_by(2): {:?}", skip_two.next());

    // nth(n) consumes n items and returns the one that lands next
    let mut by_nth = letters.iter();
    println!("nth(3): {:?}", by_nth.nth(3));
    println!("then next(): {:?}", by_nth.next());

    // past the end, advance_by reports the shortfall instead of panicking
    let mut exhausted = letters.iter();
    let shortfall = match exhausted.advance_by(10) {
        Ok(()) => 0,
        Err(k) => k.get(),
    };
    println!("advance_by(10) shortfall: {shortfall}, next: {:?}", exhausted.next());
}