slice::iter¶
Level: reference · for working programmers
One line: An iterator over &T — what for x in &v calls, and the door to every adapter.
Stable since 1.0.0. Its const form is still unstable.
v.iter() yields references, &T, and borrows the slice for as long as the iterator lives. for x in &v is the same call — &Vec<T> and &[T] implement IntoIterator by calling iter() — so the explicit form is for the chain: v.iter().map(…), .filter(…), .sum(), .position(…), collect.
Because the items are &T, closures see references: filter(|&&x| x > 1) for a Vec<i32>, or *x inside. That double & is the one that trips people — filter hands its closure a reference to the item, and the item is already a reference.
The iterator is double-ended and exact-size: .rev() works and .len() is free. And it is the home of the searches contains cannot do — position returns the index, any takes a predicate, find returns the element.
iter_mut yields &mut T; Vec::into_iter yields T and consumes the vector. Three iterators, three kinds of item, and one page on choosing.
Example¶
slice_iter.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let v = vec![1, 2, 3];
for x in v.iter() {
print!("{x} ");
}
println!("<- same as `for x in &v`");
let total: i32 = v.iter().sum();
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
println!("{total} {doubled:?}");
// Items are &T, so filter's closure sees &&i32: destructure or deref.
let big = v.iter().filter(|&&x| x > 1).count();
println!("{big}");
// The searches contains() cannot do.
println!("{:?} {:?}", v.iter().position(|&x| x == 2), v.iter().find(|&&x| x > 5));
// It borrows: v is intact afterwards. into_iter() would have consumed it.
println!("{v:?}");
// Double-ended and exact-size.
println!("{:?} {}", v.iter().rev().collect::<Vec<_>>(), v.iter().len());
}
Verified output of slice_iter.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
slice::iter_mut— the same over&mut Tslice::contains— the one search that needs no iteratorslice::chunks— iterate in groupsslice::windows— iterate in overlapping groups