Sub topic 9
Useful slice methods and iterators
This chapter assumes you know how to create slices with ranges, the difference between &[T] and &mut [T], and how Option and Result work. Slice methods are defined on [T], so they work on arrays, vectors, and any sub-slice. Most of them return borrowed views or lazy iterators, so they don't copy data.
Iterating over elements
iter() yields &T. iter_mut() yields &mut T. into_iter() on a Vec yields owned values, but on a slice reference it yields references.
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6, 7];
for x in v.iter_mut() {
*x *= 2;
}
let total: i32 = v.iter().sum();
println!("{}", total);
let chunks = v.chunks_exact(3);
println!("{:?}", chunks.remainder());
for c in chunks {
println!("{:?}", c);
}
}This prints 56, then [14], then [2, 4, 6] and [8, 10, 12]. The chunks_exact iterator skips the short last piece. You read that piece with remainder().
Sliding and fixed-size groups
windows(n) yields overlapping sub-slices of length n. chunks(n) yields non-overlapping sub-slices. The last chunk may be shorter than n.
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]. The chunks are [1, 2], [3, 4], and [5].
Splitting, searching, and peeking
split_at(mid) returns two slices, [..mid] and [mid..]. first() and last() return Option<&T>, so an empty slice gives None instead of a panic. contains(&x) does a linear scan.
binary_search(&x) needs a sorted slice. It returns Ok(index) when it finds the value. Otherwise it returns Err(index), where index is the position that would keep the slice sorted.
fn main() {
let sorted = [1, 3, 5, 7, 9];
println!("{:?}", sorted.binary_search(&7));
println!("{:?}", sorted.binary_search(&4));
let (head, tail) = sorted.split_at(2);
println!("{:?} {:?}", head, tail);
println!("{:?} {:?}", sorted.first(), sorted.last());
println!("{}", sorted.contains(&5));
}The output is Ok(3), Err(2), [1, 3] [5, 7, 9], Some(1) Some(9), and true.
Quick reference
| Method | Returns | Notes |
|---|---|---|
| `iter()` | Iterator of `&T` | Read-only pass |
| `iter_mut()` | Iterator of `&mut T` | Edit in place |
| `windows(n)` | Iterator of `&[T]` | Overlapping, panics if `n == 0` |
| `chunks(n)` | Iterator of `&[T]` | Last chunk may be short, panics if `n == 0` |
| `chunks_exact(n)` | Iterator of `&[T]` | Drops the short tail, available via `remainder()` |
| `split_at(i)` | `(&[T], &[T])` | Panics if `i > len` |
| `binary_search(&x)` | `Result<usize, usize>` | Slice must be sorted |
| `first()`, `last()` | `Option<&T>` | `None` when empty |
Common errors
- Zero sizes.
windows(0),chunks(0), andchunks_exact(0)panic. Validate user-supplied sizes first. - Short input. If the slice is shorter than
n,windows(n)yields nothing.chunks(n)yields one short chunk. - Holding an iterator while mutating.
v.iter()borrowsvimmutably for as long as the iterator lives. Callingv.push(...)inside the loop is a borrow error. Collect indices or results first, then mutate. - Unchecked
split_at. It panics when the index is out of range. For untrusted indices, checki <= s.len()before calling it.
Exercise
Write a function is_strictly_increasing(s: &[i32]) -> bool using a slice method from this chapter. What does it return for an empty slice and for a one-element slice?
Show answer
fn isstrictlyincreasing(s: &[i32]) -> bool { s.windows(2).all(|w| w[0] < w[1]) }. Both an empty slice and a one-element slice yield no windows, so all returns true for both.
Exercise
Given let s = [2, 4, 6, 8];, what do s.binary_search(&5) and s.chunks(3).count() return?
Show answer
binary_search(&5) returns Err(2), because 5 would be inserted between 4 and 6. chunks(3) gives [2, 4, 6] and [8], so the count is 2.