In Rust, how does Iterator::peekable let you total consecutive paginated records per account, and what do Peekable's peek and next_if return?
answer
- a one-item buffer
- look without consuming
- peek borrows mutably
- consume only on a match
- double references from slice iterators
basics
~20 sCalling peekable() wraps an iterator in Peekable, which buffers one item. peek returns Option<&Item> without consuming; next_if(pred) returns Some(item) and consumes it only when the predicate accepts it, otherwise None and the item stays buffered.
solid answer
~50 s`Iterator::peekable` returns `Peekable<I>`, which stores the item it has pulled from the inner iterator but not yet handed out. `Peekable::peek(&mut self)` returns `Option<&I::Item>`: it calls the inner `next` at most once and keeps the result, even a `None`. `Peekable::next_if(|r| r.account == first.account)` returns `Some(record)` and consumes it when the predicate holds, and otherwise returns `None` and leaves it for the next call — exactly what grouping consecutive records needs: take the first record, then loop on `next_if` while the account matches. `peek` takes `&mut self`, so the binding must be `let mut` (E0596 otherwise), and the returned reference borrows the `Peekable`, so calling `next` while holding it is E0499. Over a slice iterator the item is already `&T`, so `peek` gives `Option<&&T>`. Peeking runs the inner iterator's work early, so peeking a paginated stream may fetch a page.
code
rust · 29 lines#[derive(Debug)]
struct Record { account: u32, cents: i64 }
fn main() {
let records = vec![
Record { account: 7, cents: 500 },
Record { account: 7, cents: 250 },
Record { account: 9, cents: 100 },
Record { account: 7, cents: 50 },
];
let mut it = records.into_iter().peekable();
let mut totals = Vec::new();
while let Some(first) = it.next() {
let mut sum = first.cents;
while let Some(r) = it.next_if(|r| r.account == first.account) {
sum += r.cents;
}
totals.push((first.account, sum));
}
println!("{totals:?}");
let ids = [1, 2, 3];
let mut p = ids.iter().peekable();
assert_eq!(p.peek(), Some(&&1));
assert_eq!(p.next_if_eq(&&1), Some(&1));
assert_eq!(p.next_if_eq(&&9), None);
assert_eq!(p.next(), Some(&2));
println!("ok");
}go deeper
Recall that peekable gives a one-item lookahead: peek shows the next item, next takes it, and the binding must be let mut.
Explain next_if and next_if_eq for grouping or parsing, why peek returns a reference, and why that reference blocks other calls on the Peekable.
Point out that peeking runs the inner iterator's side effects early, that Peekable is fused only when its inner iterator is, and when one item of lookahead is not enough.
Judge whether a parser or stream API should expose Peekable to callers or hide the lookahead behind its own methods, keeping buffering an internal detail.
## What Peekable adds A Rust iterator only moves forward: `next` hands out an item and it is gone. Many parsers and grouping loops need to look at the upcoming item before deciding whether to take it. `Iterator::peekable(self)` wraps any iterator in the adapter `Peekable<I>`, which has a one-item buffer. In the library source its state is an `Option<Option<I::Item>>`: the outer `Option` says whether something has been peeked, the inner one remembers what was seen — including a `None`, so peeking twice at the end does not call the inner iterator twice. | Method | Argument | Returns | Effect | |---|---|---|---| | `peek` | none | `Option<&Item>` | fills the buffer if empty, lends a shared reference | | `peek_mut` | none | `Option<&mut Item>` | same, but lets you change the buffered item | | `next_if` | `impl FnOnce(&Item) -> bool` | `Option<Item>` | consumes the next item only if the predicate is true | | `next_if_eq` | `&T` | `Option<Item>` | consumes the next item only if it equals the argument | | `next` | none | `Option<Item>` | hands out the buffered item first, then pulls from the inner iterator | All of them take `&mut self`. `next_if` and `next_if_eq` arrived in Rust 1.51 and `peek_mut` in 1.53. Rust 1.94 added `next_if_map` and `next_if_map_mut`, which consume the next item only when a mapping succeeds and return the mapped value. ## Grouping consecutive records A paginated API returns records in order, and you want one total per run of the same account: ```rust let mut it = records.into_iter().peekable(); while let Some(first) = it.next() { let mut sum = first.cents; while let Some(r) = it.next_if(|r| r.account == first.account) { sum += r.cents; } totals.push((first.account, sum)); } ``` 1. `it.next()` takes the first record of a run. 2. `next_if` consumes each following record while the predicate holds. 3. When it sees a different account, `next_if` returns `None` and **puts the record back** in the buffer, so the outer loop's next `next()` starts the new run with it. Without `Peekable` you would have to carry the "one too far" record in a separate variable. Records 7, 7, 9, 7 produce `[(7, 750), (9, 100), (7, 50)]` — consecutive grouping, not a total per account across the whole stream. ## The borrow rules around peek - **The binding must be mutable.** `peek` may call the inner `next`, so it takes `&mut self`. `let it = v.into_iter().peekable(); it.peek()` fails with E0596, "cannot borrow `it` as mutable, as it is not declared as mutable". - **The reference ties up the Peekable.** `if let Some(head) = it.peek() { it.by_ref().collect() ... }` fails with E0499, because `head` still borrows `it` mutably when the second mutable borrow starts. Copy or clone what you need out of the reference first, or use `next_if`. - **Double references.** Over `slice.iter()` the item type is already `&T`, so `peek()` returns `Option<&&T>` and `next_if_eq` needs `&&value`. std's own documentation calls this out as a possibly confusing situation. ## Peeking does real work The buffer is filled by calling the inner iterator's `next`, so any side effect runs at peek time. With a lazy `map` that logs, the log line appears at the first `peek`, not at the later `next`. For a paginated client that fetches when its buffer runs dry, peeking past the end of one page fetches the next page early. `Peekable` remembers a `None` it peeked, but that does not make the iterator fused: after the remembered `None` is handed out, a further `next` asks the inner iterator again, and `Peekable<I>` implements `FusedIterator` only when `I` does. ## When to use it - Tokenisers and parsers that decide by the next character or token. - Run-length grouping, merging sorted streams and "take while, but keep the first non-match". - Any loop that would otherwise keep a hand-rolled "pending item" variable. `next_if_map` fits the parsing case: `iter.next_if_map(|c| c.to_digit(10).ok_or(c))` over a `Peekable<Chars>` consumes a character only when it is a digit and returns its value, handing a non-digit back to the buffer for the next step. When you need to look further ahead than one item, `Peekable` is the wrong tool; buffer into a `VecDeque` or work on a slice with `windows`.
- Does peeking at a Peekable cause the inner iterator to do work early?Yes. `peek` fills the buffer by calling the inner `next`, so a lazy `map` with side effects, or a paginated client that fetches when it runs dry, does that work at peek time. Repeated peeks do not repeat it; the buffered item is reused.
- What did Rust 1.94 add to Peekable, and when would you use it?`next_if_map` and `next_if_map_mut`. `next_if_map` passes the next item by value to a closure returning `Result<R, Item>`; `Ok` consumes it and yields the mapped value, `Err` hands the item back to the buffer. It suits parsing a token into a value only when it has the right shape.
- peek takes &self, so an immutable binding is enough.
- next_if drops the item when the predicate is false.
- Peeking twice advances the inner iterator twice.
- Peekable makes any iterator fused because it remembers None.
- peek returns the item by value, so you can keep it after calling next.
Assumes Rust 1.99; next_if and next_if_eq have been stable since 1.51, peek_mut since 1.53, and next_if_map since 1.94.