next()
The next(&mut self) -> Option<Self::Item> method is the single required method on the Iterator trait, advancing the iterator's internal state by one element and returning Some(element) or None when no elements remain.
Calling next() Manually
Because next() mutates the iterator's internal cursor or state to advance to the next item, the variable holding the iterator must be declared let mut:
fn main() {
let primes = [2, 3, 5];
let mut iter = primes.iter();
println!("1st call: {:?}", iter.next());
println!("2nd call: {:?}", iter.next());
println!("3rd call: {:?}", iter.next());
println!("4th call: {:?}", iter.next());
}
1st call: Some(&2)
2nd call: Some(&3)
3rd call: Some(&5)
4th call: None
Step 0: iter ──> [ 2, 3, 5 ]
Step 1: iter.next() -> Some(&2) iter ──> [ 3, 5 ]
Step 2: iter.next() -> Some(&3) iter ──> [ 5 ]
Step 3: iter.next() -> Some(&5) iter ──> [ ]
Step 4: iter.next() -> None iter ──> [ ] (Exhausted)
Requiring let mut When Calling next() (E0596)
Attempting to call .next() on an immutable iterator variable fails at compile time with E0596:
// ❌ does not compile
fn main() {
let items = [10, 20];
let iter = items.iter();
let first = iter.next();
}
error[E0596]: cannot borrow `iter` as mutable, as it is not declared as mutable
--> src/main.rs:5:17
|
4 | let iter = items.iter();
| ---- help: consider changing this to be mutable: `mut iter`
5 | let first = iter.next();
| ^^^^ cannot borrow as mutable
(When you use a for x in items.iter() loop, you do not write mut yourself because the compiler's for-loop desugaring binds let mut iter = IntoIterator::into_iter(...) internally.)
Advancing an Iterator Partially Before a Loop
Calling .next() manually before passing the remaining iterator to a for loop or .collect() is a common pattern for extracting a header row or initial element:
fn main() {
let csv_lines = ["id,name", "1,Alice", "2,Bob"];
let mut lines = csv_lines.into_iter();
if let Some(header) = lines.next() {
println!("Header: {header}");
for row in lines {
println!(" Row: {row}");
}
}
}
Header: id,name
Row: 1,Alice
Row: 2,Bob