next is the core iterator method in Rust. Each call advances the iterator and returns an Option: Some(item) while an item remains, then None when iteration has ended. section 8.2 section 8.4
Iterators are lazy, so creating one does not consume its items. Calling next manually gives direct control; for loops repeatedly call it until None, while methods such as collect can drive the iteration. section 8.2 section 8.4
Checking each item
let mut letters = vec!['a', 'b', '거', '柳'].iter(); assert_eq!(letters.next(), Some(&'a')); assert_eq!(letters.next(), Some(&'b')); assert_eq!(letters.next(), Some(&'거')); assert_eq!(letters.next(), Some(&'柳')); assert_eq!(letters.next(), None); assert_eq!(letters.next(), None); section 8.2
Implementing Iterator for a custom type requires next to:
- Update the iterator's internal state. section 8.2
- Return Some(value) when another item is available. section 8.2
- Return None when iteration has finished; specialized iterators may deliberately behave differently. section 8.2
fn main() {
let my_vec = vec!['a', 'b', '거', '柳']; #1
let mut my_vec_iter = my_vec.iter(); #2
assert_eq!(my_vec_iter.next(), Some(&'a')); #3
assert_eq!(my_vec_iter.next(), Some(&'b'));
assert_eq!(my_vec_iter.next(), Some(&'거'));
assert_eq!(my_vec_iter.next(), Some(&'柳'));
assert_eq!(my_vec_iter.next(), None); #4
assert_eq!(my_vec_iter.next(), None); #5
}
Trace successive next calls from the first item through the terminal None result. section 8.2




