Sub topic 11
Useful array methods: len, contains, map, and more
This chapter assumes you can declare arrays, index them, and borrow them with &. It covers the methods you will reach for most often. Most of them come from slices, because an array automatically borrows as a slice when you call a method on it. A few, such as map, belong to the array type itself.
Inspecting an array
These methods only read the array. They take &self, so the array stays usable afterwards.
len()returns the number of elements. For an array this equals theNin[T; N].is_empty()returnstruewhen the length is zero.contains(&x)returnstrueif any element equalsx. It needsT: PartialEqand takes a reference.first()andlast()returnOption<&T>, so an empty array givesNone.iter().position(...)finds the index of the first match.
fn main() {
let scores = [72, 88, 95, 60];
println!("{}", scores.len());
println!("{}", scores.is_empty());
println!("{}", scores.contains(&95));
println!("{:?} {:?}", scores.first(), scores.last());
println!("{:?}", scores.iter().position(|&s| s == 88));
}A common error is writing scores.contains(95). The method expects &i32, so the compiler rejects a plain 95. Write contains(&95).
Transforming with map
map is defined on arrays, not on slices. It consumes the array, applies a closure to each element, and returns a new array of the same length. The element type can change.
fn main() {
let celsius = [0.0_f64, 21.5, 100.0];
let fahrenheit = celsius.map(|c| c * 9.0 / 5.0 + 32.0);
println!("{:?}", fahrenheit);
let labels = [1, 2, 3].map(|n| format!("item{n}"));
println!("{:?}", labels);
}The result is still [T; N], so the length is known at compile time. Calling iter().map(...) is different. It builds a lazy iterator, and you must collect it into a Vec or another container.
Sorting, reversing, and filling
Methods that change an array need a mut binding.
fn main() {
let mut data = [5, 3, 8, 1];
data.sort();
println!("{:?}", data);
data.reverse();
println!("{:?}", data);
data.swap(0, 3);
println!("{:?}", data);
data.fill(7);
println!("{:?}", data);
}sort works on any T: Ord. Floats are not Ord because of NaN, so use sort_by(|a, b| a.partial_cmp(b).unwrap()) for them. swap panics if an index is out of bounds.
Splitting and joining views
Because these are slice methods, they return borrowed views and copy nothing.
fn main() {
let data = [1, 2, 3, 4, 5, 6];
let (left, right) = data.split_at(2);
println!("{:?} {:?}", left, right);
for pair in data.chunks(4) {
println!("{:?}", pair);
}
for w in data.windows(3) {
print!("{} ", w.iter().sum::<i32>());
}
println!();
}chunks(n) yields non-overlapping pieces, and the last one may be shorter. windows(n) yields overlapping pieces, each exactly n long.
| Method | Needs `mut` | Returns |
|---|---|---|
| `len` | no | `usize` |
| `contains` | no | `bool` |
| `map` | no (consumes array) | new `[U; N]` |
| `sort` | yes | `()` |
| `split_at` | no | two slices |
| `windows` | no | iterator of slices |
Exercise
You have let a = [1, 2, 3];. What is the type of a.map(|x| x as f64 * 0.5), and why does a.contains(2) fail to compile?
Show answer
The type is [f64; 3], because map on an array returns an array of the same length with the closure's output type. a.contains(2) fails because contains takes a reference to the element, so it must be written a.contains(&2).