Skip to content

iterators

https://doc.rust-lang.org/book/ch13-02-iterators.html

Iterators in rust let you iterate over a vector/array/strings.

When you write

fn main() {
let v = vec![1, 2, 3];
for i in v {
println!("{}", i);
}
}

This under the hood gets converted to

fn main() {
let v = vec![1, 2, 3];
let mut v_iter = v.into_iter();
while let Some(i) = v_iter.next() {
print!("{}", i);
}
}

Iter

Iter doesn’t consume the original variable and it can be used afterwards

fn main() {
let v = vec![1, 2, 3];
let mut v_iter = v.iter();
while let Some(i) = v_iter.next() {
print!("{}", i);
}
println!("{:?}", v);
}

IntoIter

IntoIter consumes the original variable and it cant be used after the intoiter is used.

fn main() {
let v = vec![1, 2, 3];
let mut v_iter = v.into_iter();
while let Some(i) = v_iter.next() {
print!("{}", i);
}
println!("{:?}", v);
}

Screenshot 2025-02-14 at 4.07.03 PM.png

Consuming adapters

Methods that call next are called consuming adapters, because calling them uses up the iterator (not the original variable but the iterator). For example - sum or count

fn main() {
let v = vec![1, 2, 3];
let v_iter = v.into_iter();
let sum: i32 = v_iter.sum();
println!("{}", sum);
// try using the iterator again here.
}

Iterator adapter

Iterator adapters are methods defined on the Iterator trait that don’t consume the iterator.Instead, they produce different iterators by changing some aspect of the original iterator.

fn main() {
let v = vec![1, 2, 3];
let v_iter = v.into_iter();
let v2: Vec<i32> = v_iter.map(|x| x + 1).collect();
println!("{:?}", v2);
}