Sub topic 3
Rust Tuples and Arrays: Fixed-Size Collections
Assume basic Rust syntax, references, borrowing, and running Cargo programs. This chapter focuses on arrays and the types built around them.
Arrays of arrays
An array can contain other arrays. Every inner array has the same type and length:
fn main() {
let grid: [[i32; 3]; 2] = [[1, 2, 3], [4, 5, 6]];
println!("{}", grid[1][2]);
}The type reads as “two arrays, each containing three i32 values.” Arrays of arrays work well for fixed-size grids and tables.
Slices: borrowing a view of an array
A slice, written &[T], is a borrowed view of consecutive elements. It does not own data and does not include the array's fixed length in its type.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let data = [10, 20, 30, 40];
println!("{}", sum(&data));
println!("{}", sum(&data[1..3]));
}The same function accepts an entire array, part of an array, or a Vec<i32>.
Matching on slices and arrays
Slice patterns let a function branch on shape:
fn describe(values: &[i32]) -> &'static str {
match values {
[] => "empty",
[_] => "one element",
[first, .., last] if first == last => "same ends",
[_, ..] => "many elements",
}
}The pattern .. means “zero or more elements.”
Writing code generic over array length
Const generics allow the array length to be a parameter:
use std::convert::TryInto;
fn first_n<const N: usize>(values: &[i32]) -> Option<[i32; N]> {
values.get(..N)?.try_into().ok()
}The function returns None when the slice contains fewer than N elements.
When an array is not enough: `Vec`
Use Vec<T> when the number of elements changes at runtime or can become large. A vector owns growable storage. Choose an array when the length is fixed and part of the design.
Where tuples and arrays live in memory
Tuples and arrays store their elements inline, usually in the stack when local. A Vec stores a small descriptor inline and its elements in a heap allocation.
Choosing the right type
| Need | Type |
|---|---|
| Fixed fields with different types | Tuple |
| Fixed number of same-type elements | Array |
| Borrowed sequence of flexible length | Slice |
| Owned sequence that grows | Vec |
Exercise
Which type should a function use to read any borrowed sequence of integers without taking ownership?
Show answer
Use &[i32], because a slice borrows a sequence and accepts arrays, subranges, and vectors.