条件消费
Peekable 的 next_if 只在谓词成立时消费下一项。parse_number 循环 next_if(|c| c.is_ascii_digit()),数字累进 value,第一个非数字留在流里——42 被吃掉,px 留下。
精确匹配变体
next_if_eq(‘p’) 只在下一字符等于 ‘p’ 时消费(got p consumed: Some(‘p’)),剩下 as_str rest: x 交给调用方。
对比手写 peek
传统写法是先 peek() 判断再 next() 取值,中间还有借用周折;next_if 把两步合成一次调用,要么消费要么原样不动。
next_if 不匹配时消耗了吗?
没有,迭代器状态完全不变,后续仍从该项读起。
peekable 与 next_if 的关系?
next_if 是 Peekable 适配器提供的方法,普通迭代器没有。
next_if 谓词不成立时会怎样?
什么都不消费,Peekable 状态不变,下次调用看到的仍是同一项。
parse_number 如何停在 px?
循环条件是 next_if(is_ascii_digit);下一个字符是 ‘p’ 时谓词失败循环结束,‘p’ 留给 next_if_eq 处理。