Sub topic 11
Useful array methods: len, contains, map, and more
This chapter assumes you can create arrays, index them, and iterate over them, as covered in the earlier chapters. You should also be comfortable with & references, &mut references, and closures. Here you will learn where array methods come from, which ones you will use most often, and the mistakes that trip people up.
Where array methods come from
An array [T; N] has only a few methods of its own. Most of the methods you call on an array belong to the slice type [T]. The compiler converts &[T; N] to &[T] automatically when you call a method, so scores.len() works without any extra syntax. This conversion is called unsized coercion.
This explains two things. First, nearly every method in this chapter also works on a Vec<T> or any other slice. Second, map is a method of arrays only. Slices and Vec do not have it, because their length is not known to the type system.
Querying: len, is_empty, contains, first, last
fn main() {
let scores = [72, 95, 88, 61, 95];
let langs = ["rust", "go", "zig"];
println!("{} {}", scores.len(), scores.is_empty());
println!("{}", scores.contains(&88));
println!("{}", langs.contains(&"go"));
println!("{:?} {:?}", scores.first(), scores.last());
}lenreturns ausize. For an array it is always theNin the type.is_emptyistrueonly for[T; 0], so it is rarely useful on arrays. It matters when the same code receives a slice.containstakes a reference to the value you are looking for, which is why you write&88. For an array of&str, you pass&"go", a reference to a&str.containsneedsT: PartialEq. An array off64works, but be aware thatNaNis never equal to anything.firstandlastreturnOption<&T>. They giveNoneinstead of panicking, which makes them safer thanscores[0]when the slice might be empty.
Comparison works too. Arrays of the same type and length support ==, and starts_with and ends_with take a slice:
fn main() {
let data = [1, 2, 3, 4, 5, 6, 7];
println!("{}", data.starts_with(&[1, 2]));
println!("{}", data.ends_with(&[7]));
println!("{}", data == [1, 2, 3, 4, 5, 6, 7]);
}Changing in place: sort, reverse, swap, fill
These methods take &mut self, so the binding must be declared mut.
fn main() {
let mut scores = [72, 95, 88, 61, 95];
scores.sort();
println!("{:?}", scores);
println!("{:?}", scores.binary_search(&88));
println!("{:?}", scores.binary_search(&90));
scores.reverse();
scores.swap(0, 4);
println!("{:?}", scores);
scores.fill(0);
println!("{:?}", scores);
}The program prints:
[61, 72, 88, 95, 95]
Ok(2)
Err(3)
[61, 95, 88, 72, 95]
[0, 0, 0, 0, 0]binary_search returns Ok(index) when it finds the value. It returns Err(index) with the position where the value could be inserted to keep the order. It only gives meaningful results on sorted data. On unsorted input it still returns something, but not a reliable answer.
sort needs T: Ord, so it does not compile for f64. Use sort_by(|a, b| a.total_cmp(b)) for floats. swap(i, j) panics if either index is out of range.
Transforming: map and from_fn
map is defined on arrays. It applies a closure to each element and returns a new array of the same length:
fn main() {
let celsius = [0, 25, 100];
let fahrenheit = celsius.map(|c| c * 9 / 5 + 32);
println!("{:?}", fahrenheit);
let names = ["ann", "bo"].map(String::from);
println!("{:?}", names);
let lengths = names.map(|n| n.len());
println!("{:?}", lengths);
}The output is [32, 77, 212], then ["ann", "bo"], then [3, 2].
The result type is [U; N], so the length is preserved by the type system. No collect is needed.
If you want to borrow instead, use the iterator form. It produces an iterator, which you usually collect into a Vec:
fn main() {
let values = [1, 2, 3];
let doubled: Vec<i32> = values.iter().map(|x| x * 2).collect();
println!("{:?} {:?}", values, doubled);
}Collecting an iterator straight into an array is not supported, because the compiler cannot prove the length. To build an array from an index, use std::array::from_fn:
fn main() {
let squares: [usize; 5] = std::array::from_fn(|i| i * i);
println!("{:?}", squares);
}This prints [0, 1, 4, 9, 16]. The array length comes from the type annotation, and the closure receives each index.
Viewing parts: windows, chunks, split_at
These slice methods return borrowed views and never copy data.
fn main() {
let data = [1, 2, 3, 4, 5, 6, 7];
for chunk in data.chunks(3) {
println!("{:?}", chunk);
}
let sorted = data.windows(2).all(|w| w[0] <= w[1]);
println!("{sorted}");
let (left, right) = data.split_at(2);
println!("{:?} {:?}", left, right);
}The output is:
[1, 2, 3]
[4, 5, 6]
[7]
[1, 2] [3, 4, 5, 6, 7]The line true is printed between the chunks and the split. chunks(n) yields non-overlapping pieces, and the last one may be shorter. windows(n) yields overlapping pieces of exactly n elements, so on [1, 2, 3, 4, 5, 6, 7], windows(2) yields six pairs. Both panic if n is 0. split_at(mid) panics if mid > len.
Quick reference
| Method | Needs `mut` | Returns | Requirement |
|---|---|---|---|
| `len` | No | `usize` | None |
| `contains(&x)` | No | `bool` | `T: PartialEq` |
| `first`, `last` | No | `Option<&T>` | None |
| `map(f)` | No, consumes the array | `[U; N]` | Closure `FnMut(T) -> U` |
| `sort` | Yes | `()` | `T: Ord` |
| `binary_search(&x)` | No | `Result<usize, usize>` | `T: Ord`, sorted input |
| `fill(v)` | Yes | `()` | `T: Clone` |
| `windows(n)`, `chunks(n)` | No | Iterator of slices | `n > 0` |
Common mistakes
- Calling
sorton a binding that is notmut. The error is "cannot borrow as mutable". - Writing
contains(88)instead ofcontains(&88). - Using
mapand then reading the original non-Copyarray. - Expecting
iter().map(...)to return an array. It returns an iterator. - Trusting
binary_searchon unsorted data.
Exercise
Given let words = ["apple", "fig", "kiwi"];, write one expression that produces an array [usize; 3] holding each word's length. Then say whether words is still usable afterwards, and why.
Show answer
let lengths = words.map(|w| w.len()); gives [5, 3, 4]. Yes, words is still usable. Array map takes the array by value, but [&str; 3] is Copy because &str is Copy, so the call copies the array instead of moving it. With an array of String the original would be moved.
Exercise
Why does let mut a = [3, 1, 2]; a.sort(); println!("{:?}", a.binary_search(&2)); print Ok(1), and what would a.binary_search(&5) return?
Show answer
After sorting, a is [1, 2, 3], and 2 is at index 1, so the search returns Ok(1). The value 5 is missing and would belong after the last element, so binary_search(&5) returns Err(3).