Consume Conditionally With Peekable next_if

next_if consumes the next item only while a predicate holds, so parsers can peel digits or an exact character with no manual peek bookkeeping.

RustData Integrity

Code

rustsnippet
22 lines
use std::iter::Peekable;
use std::str::Chars;

fn parse_number(tokens: &mut Peekable<Chars<'_>>) -> u32 {
    let mut value = 0u32;
    // 只有下一个字符是数字才消费:peek 的判断 + next 的取值一步完成
    while let Some(digit) = tokens.next_if(|c| c.is_ascii_digit()) {
        value = value * 10 + digit.to_digit(10).expect("checked digit");
    }
    value
}

fn main() {
    let mut tokens = "42px".chars().peekable();
    let width = parse_number(&mut tokens);
    println!("width: {width}");

    // next_if_eq:只在等于给定值时消费,不匹配则原样保留
    let got_p = tokens.next_if_eq('p');
    println!("p consumed: {got_p:?}");
    println!("rest: {}", tokens.as_str());
}

Conditional consumption

Peekable’s next_if consumes the next item only while the predicate holds. parse_number loops next_if(|c| c.is_ascii_digit()) so digits accumulate into value and the first non-digit stays in the stream — 42 is eaten from 42px and the px remains.

Exact-match variant

next_if_eq(‘p’) consumes only when the next char equals ‘p’ (got p consumed: Some(‘p’)), leaving as_str rest: x for the caller.

Against manual peek

The classic alternative is peek() to test then next() to consume, with the borrow dance between them; next_if folds both into one call that either consumes or leaves everything untouched.

Interactive Tools for This Topic

FAQ

What happens when next_if's predicate fails?
Nothing is consumed; the Peekable keeps its state and the next call sees the same item.
How does parse_number stop at px?
The loop condition is next_if(is_ascii_digit); once the next char is 'p' the predicate fails, the loop ends, and 'p' stays for the next_if_eq step.