Sub topic 9
Useful slice methods and iterators
Slices carry many methods for reading, searching, sorting, and splitting contiguous data. This chapter covers the ones you will use most. It assumes you know the slice type &[T], range syntax such as &v[1..4], and the difference between indexing and get. It also assumes basic familiarity with closures and iterator adapters like map and filter.
Every method here is defined on [T], not on Vec<T> or [T; N]. Arrays and vectors reach these methods through automatic dereferencing, so vec.windows(2) and array.windows(2) both work. A method that takes &self borrows the data immutably. A method that takes &mut self needs a mutable slice and cannot run while other borrows are alive.
Iterating: iter, iter_mut, and into_iter
A slice offers three ways to walk its elements.
| Call | Item type | Use it when |
|---|---|---|
| `slice.iter()` | `&T` | You only read the elements |
| `slice.iter_mut()` | `&mut T` | You change elements in place |
| `vec.into_iter()` | `T` | You consume a `Vec` and take ownership of each element |
into_iter on a slice reference behaves like iter. for x in &slice is shorthand for slice.iter(), and for x in &mut slice is shorthand for slice.iter_mut().
fn main() {
let mut v = vec![3, 1, 4, 1, 5];
for x in v.iter_mut() {
*x *= 2;
}
let total: i32 = v.iter().sum();
println!("{:?} total={}", v, total);
}This prints [6, 2, 8, 2, 10] total=28. Because iter() yields references, closures in adapters receive references too. filter adds one more level, since it passes &Item to its closure. That makes the argument type &&i32 when you filter iter(). You can destructure it in the pattern, or call copied() first.
fn main() {
let v = [1, 5, 2, 8, 3];
let big: Vec<i32> = v.iter().filter(|&&x| x > 2).copied().collect();
let also_big: Vec<i32> = v.iter().copied().filter(|x| *x > 2).collect();
println!("{:?} {:?}", big, also_big);
}Both lines produce [5, 8, 3]. copied() works for Copy types, and cloned() works for anything that implements Clone.
Reading without iterating
Several small methods answer common questions without a loop.
fn main() {
let v = [10, 20, 30, 40];
println!("{} {}", v.len(), v.is_empty());
println!("{:?} {:?}", v.first(), v.last());
println!("{}", v.contains(&30));
println!("{}", v.starts_with(&[10, 20]));
println!("{:?}", v.iter().position(|&x| x == 30));
}The output is:
4 false
Some(10) Some(40)
true
true
Some(2)first and last return Option<&T>, so an empty slice gives None and never panics. contains takes a reference to the value you are looking for. It needs T: PartialEq and checks every element, so it is O(n).
Splitting a slice
split_at divides one slice into two at an index. split_first and split_last peel off one element and return an Option.
fn main() {
let data = [1, 2, 3, 4, 5];
let (a, b) = data.split_at(2);
println!("{:?} {:?}", a, b);
if let Some((head, tail)) = data.split_first() {
println!("{} then {:?}", head, tail);
}
}This prints [1, 2] [3, 4, 5] and then 1 then [2, 3, 4, 5]. split_at panics if the index is greater than the length. Index equal to the length is allowed and gives an empty second slice. split_first is a handy way to write recursive functions over slices.
To split on a condition, use split with a predicate. Elements matching the predicate act as separators and are not included in the pieces.
fn main() {
let data = [1, 0, 2, 3, 0, 4];
for part in data.split(|&x| x == 0) {
println!("{:?}", part);
}
}The pieces are [1], [2, 3], and [4].
Windows and chunks
windows(n) yields every run of n consecutive elements. The runs overlap, so the iterator produces len - n + 1 items. chunks(n) yields non-overlapping pieces of up to n elements, and the last piece may be shorter.
fn main() {
let data = [1, 2, 3, 4, 5];
let sums: Vec<i32> = data.windows(2).map(|w| w[0] + w[1]).collect();
println!("{:?}", sums);
for c in data.chunks(2) {
println!("{:?}", c);
}
}The sums are [3, 5, 7, 9], and the chunks are [1, 2], [3, 4], and [5].
Some edge cases matter in practice:
windows(0)andchunks(0)panic. Validate sizes that come from user input.- If the window size is larger than the slice,
windowsyields nothing. It does not panic. chunks_exact(n)skips the short final piece. You can read it afterwards withremainder().chunks_mut(n)gives mutable, non-overlapping pieces. There is nowindows_mut, because overlapping mutable borrows would break the aliasing rules.
fn main() {
let data = [1, 2, 3, 4, 5, 6, 7];
let it = data.chunks_exact(3);
println!("remainder: {:?}", it.remainder());
for c in it {
println!("{:?}", c);
}
let mut buf = [0u8; 6];
for (i, chunk) in buf.chunks_mut(2).enumerate() {
chunk.fill(i as u8 + 1);
}
println!("{:?}", buf);
}The remainder is [7], the chunks are [1, 2, 3] and [4, 5, 6], and buf ends up as [1, 1, 2, 2, 3, 3].
Searching a sorted slice
binary_search finds a value in O(log n) steps, but only if the slice is already sorted. It returns Result<usize, usize>. Ok(i) means the value is at index i. Err(i) means it is absent and would have to be inserted at index i to keep the order.
fn main() {
let sorted = [1, 3, 5, 7, 9];
println!("{:?}", sorted.binary_search(&7));
println!("{:?}", sorted.binary_search(&4));
let mut v = vec![1, 3, 5, 7];
let pos = v.binary_search(&4).unwrap_or_else(|i| i);
v.insert(pos, 4);
println!("{:?}", v);
}The output is Ok(3), Err(2), and [1, 3, 4, 5, 7]. Both Ok and Err hold an index, so unwrap_or_else(|i| i) gives an insertion point either way.
Sorting and rearranging in place
These methods need a mutable slice and change the order of its elements without allocating a new collection.
fn main() {
let mut words = vec!["pear", "fig", "banana", "kiwi"];
words.sort();
println!("{:?}", words);
words.sort_by_key(|w| w.len());
println!("{:?}", words);
let mut f = [2.5, -1.0, 9.75, 0.0];
f.sort_by(|a, b| a.total_cmp(b));
println!("{:?}", f);
let mut n = [1, 2, 3, 4, 5];
n.reverse();
n.swap(0, 4);
n.rotate_left(1);
println!("{:?}", n);
}The four prints are ["banana", "fig", "kiwi", "pear"], then ["fig", "kiwi", "pear", "banana"], then [-1.0, 0.0, 2.5, 9.75], then [2, 3, 4, 5, 1]. Here is how the last line is built. Reversing gives [5, 4, 3, 2, 1], swapping the ends gives [1, 4, 3, 2, 5], and rotating left by one gives [4, 3, 2, 5, 1]. Check that trace against the output before you rely on it. The real result of rotate_left(1) on [1, 4, 3, 2, 5] is [4, 3, 2, 5, 1], so the final print is [4, 3, 2, 5, 1].
A few notes on these methods:
sortis stable, so equal elements keep their relative order.sort_unstableis usually faster and uses no extra memory, but it may reorder equal elements.f64does not implementOrd, sosort()will not compile for floats. Usesort_bywithtotal_cmp, or withpartial_cmp(...).unwrap()if you are sure there are no NaN values.sort_by_keycalls the key function many times. Usesort_by_cached_keywhen computing the key is expensive.
Copying and filling
fill sets every element to one value. copy_from_slice copies from another slice into this one, and it needs T: Copy. clone_from_slice does the same for Clone types. Both panic if the two slices have different lengths.
fn main() {
let mut buf = [0; 6];
buf[..3].copy_from_slice(&[7, 8, 9]);
buf[3..].fill(1);
println!("{:?}", buf);
let copy: Vec<i32> = buf[1..4].to_vec();
println!("{:?}", copy);
}This prints [7, 8, 9, 1, 1, 1] and [8, 9, 1]. to_vec allocates a new owned Vec from a slice, which is the usual way to leave the borrowed world.
Combining slices
concat joins a slice of slices into one Vec. join does the same with a separator between the pieces. For strings, join is how you glue pieces together.
fn main() {
let parts = [[1, 2], [3, 4]];
println!("{:?}", parts.concat());
let words = ["a", "b", "c"];
println!("{}", words.join("-"));
}The output is [1, 2, 3, 4] and a-b-c.
Choosing a method
The right method often replaces a manual index loop. Manual loops risk off-by-one errors and add bounds checks that the compiler may not remove. The iterator forms state your intent and are usually as fast.
| You want to... | Reach for |
|---|---|
| Compare neighbouring elements | `windows(2)` |
| Process fixed-size batches | `chunks`, or `chunks_exact` when a short tail is not allowed |
| Test whether a value is present | `contains`, or `binary_search` if sorted |
| Find where something is | `iter().position(...)` |
| Edit non-overlapping parts at once | `chunks_mut`, `split_at_mut` |
| Get an owned copy | `to_vec` |
Common mistakes
- Searching an unsorted slice with
binary_search. The result is meaningless. Sort first, or usecontainsorposition. - Passing a zero size to
windowsorchunks. Both panic. - Expecting
iter()to yield values. It yields references. Usecopied()or dereference with*. - Using
copy_from_slicewith slices of different lengths. It panics instead of copying the shorter part. Slice both sides to the same range first. - Holding an
iter()borrow while mutating the vector. The borrow checker rejects pushing to aVecinside a loop overv.iter(). Collect the changes first, or iterate by index.
Exercise
What does [1, 2, 3].windows(4).count() return, and does it panic?
Show answer
It returns 0 and does not panic. When the window size is larger than the slice, windows yields no items. Only a window size of 0 panics.
Exercise
For let data = [1, 2, 3, 4, 5, 6, 7];, how many items does data.chunks_exact(3) produce, and what does remainder() return?
Show answer
It produces 2 chunks, [1, 2, 3] and [4, 5, 6]. remainder() returns [7], the leftover elements that did not fill a whole chunk.
Exercise
You call binary_search(&4) on the sorted slice [1, 3, 5, 7]. What is returned, and how would you use it to insert 4 in order?
Show answer
It returns Err(2), because 4 is absent and belongs at index 2. Call v.insert(2, 4). In general, let pos = v.binary_search(&x).unwrap_or_else(|i| i); v.insert(pos, x); works whether or not x is already present.