Peekable Iterator Lookahead Parsing
Parse token streams with peekable: inspect the next item without consuming it, commit with next only after a match, and merge consecutive runs into groups.
Code
#[derive(Debug, PartialEq)]
enum Token {
Num(i64),
Plus,
}
fn tokenize(input: &str) -> Vec<Token> {
input
.split_whitespace()
.map(|part| match part {
"+" => Token::Plus,
other => Token::Num(other.parse().unwrap_or(0)), // demo tokenizer
})
.collect()
}
fn main() {
let tokens = tokenize("1 2 + 3 4");
let mut iter = tokens.iter().peekable();
while let Some(&token) = iter.peek() {
match token {
Token::Num(n) => {
let mut sum = *n;
iter.next(); // peek 只看不取,确认后才消费
while let Some(&Token::Num(next)) = iter.peek() {
sum += next;
iter.next();
}
println!("group sum: {sum}");
}
Token::Plus => {
iter.next(); // 跳过分隔符
}
}
}
}How it works
Peekable Iterator Lookahead Parsing reduces to the functions tokenize and main.
The one repetition in this snippet is the loop while let Some(&token) = iter.peek(). Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Putting it to use
The main signature reads fn tokenize(input: &str) -> Vec<Token>
Running the file prints labeled results such as group sum: — each operation’s effect is visible in the output.
The entry point wires tokenize together — run it once and the whole demo flows.
Core lines
while let Some(&Token::Num(next)) = iter.peek() {
sum += next;
iter.next();
}
.map(|part| match part {
"+" => Token::Plus,
other => Token::Num(other.parse().unwrap_or(0)), // demo tokenizer
})
other => Token::Num(other.parse().unwrap_or(0)), // demo tokenizer
})
.collect()
}
Interactive Tools for This Topic
FAQ
- What does Peekable Iterator Lookahead Parsing print when run?
- No setup needed: run the file and look for labeled lines like `group sum:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.