Sub topic 18
Choosing the right type
This chapter assumes you know how to build and index tuples and arrays, borrow a slice with &[T], and create a Vec. It focuses on how to pick among tuples, arrays, slices, and Vec, and on the mistakes that picking wrongly causes.
Four types, four questions
The four types answer different questions. Ask them in this order:
- Are the values of different types, or do they have different meanings? Use a tuple, or a struct.
- Are they all one type? Then ask whether the length is known at compile time and never changes. If so, use an array.
- Does the length vary, or is it only known at run time? Use a
Vec. - Do you only need to read or modify existing elements without owning them? Take a slice in the function signature.
Tuples: use them briefly
A tuple fits best when the grouping is short-lived. The usual case is a function that returns two or three related values, such as (min, max). The caller destructures the result immediately, so the positions never need documenting.
Tuples start to hurt when they live longer. (f64, f64, f64) could be RGB, a position, or a velocity, and .1 tells the reader nothing. Two fields of the same type are easy to swap, and the compiler cannot catch it. Once a grouping is stored in a field, passed through several functions, or has more than about three components, switch to a struct. A struct costs a few lines and gives each field a name.
Tuples are also a good fit when you need their built-in trait support. A tuple is Debug, PartialEq, Ord, Default, and Copy whenever all its elements are. That makes (priority, name) a convenient sort key.
Arrays: use them when the length is part of the meaning
An array's length is part of its type, so [u8; 4] and [u8; 5] are different types. Choose an array when the length is a fact about the problem:
- the days of a week,
[&str; 7] - an IPv4 address,
[u8; 4] - a 3×3 board,
[[u8; 3]; 3] - a lookup table built at compile time
Arrays live inline, wherever the variable lives. A local array sits on the stack and costs no heap allocation. The same is true of a tuple. The cost is that a very large array, for example [u8; 10_000_000], can overflow the stack. It is also copied wholesale when moved or copied, so it can be expensive to pass by value. Large fixed-size data usually belongs in a Vec or a Box<[T]>.
Do not choose an array merely because you have a number in hand. [0; n] with a run-time n does not compile, because array lengths must be constants. That is the signal that you need a Vec.
Vec: use it when the size is not a compile-time fact
A Vec<T> stores its elements on the heap and can grow and shrink. Choose it when you read input, collect the results of an iterator, or build a list incrementally. The cost is one heap allocation and a pointer, length, and capacity stored alongside. For most programs that cost is negligible. Reaching for an array to avoid it is a premature optimization unless profiling says otherwise.
Slices: the default for function parameters
A function should rarely take Vec<T> or [T; N] when it only reads the data. Take &[T] instead. One signature then accepts an array, a Vec, or a sub-range of either. Use &mut [T] if the function modifies elements in place but does not add or remove any.
Take &Vec<T> only if you need Vec-specific methods such as push or capacity. In that case &mut Vec<T> is usually what you actually want.
The reverse also matters. Return an owned type. A function cannot return a slice of a local array, since the array dies with the function. Return a Vec, or an array if the length is fixed.
A worked example
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let first = *values.first()?;
Some(values.iter().fold((first, first), |(lo, hi), &v| {
(lo.min(v), hi.max(v))
}))
}
fn main() {
// Fixed length that is part of the problem: an array.
let weekdays: [&str; 5] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
// Number of readings is decided while running: a Vec.
let mut readings: Vec<i32> = Vec::new();
for (i, day) in weekdays.iter().enumerate() {
let value = ((i as i32 + 1) * 3) % 7;
readings.push(value);
println!("{day}: {value}");
}
// The function takes a slice, so a Vec works here...
match min_max(&readings) {
Some((lo, hi)) => println!("min={lo} max={hi}"),
None => println!("no data"),
}
// ...and so does an array, including an empty one.
let empty: [i32; 0] = [];
println!("{:?}", min_max(&empty));
}Each type does one job. The array holds the five fixed day names. The Vec holds readings that are pushed in a loop. The &[i32] parameter lets min_max accept either. The (i32, i32) tuple carries two results out and is destructured at once. Option covers the empty case.
Converting between the types
The types convert in predictable ways, and the conversions that can fail return a Result.
| From | To | How | Can fail? |
|---|---|---|---|
| `[T; N]` | `&[T]` | `&array` or `&array[..]` | No |
| `[T; N]` | `Vec<T>` | `Vec::from(array)` or `array.to_vec()` | No |
| `Vec<T>` | `&[T]` | `&vec` or `vec.as_slice()` | No |
| `&[T]` | `[T; N]` | `slice.try_into()` (needs `T: Copy`) | Yes, if the length differs |
| `Vec<T>` | `[T; N]` | `vec.try_into()` | Yes, if the length differs |
| `Vec<T>` | `Box<[T]>` | `vec.into_boxed_slice()` | No |
fn main() {
let v = vec![1, 2, 3];
let ok: Result<[i32; 3], _> = v.clone().try_into();
let bad: Result<[i32; 4], _> = v.try_into();
println!("{} {}", ok.is_ok(), bad.is_err());
}The failed Vec conversion hands the original vector back inside the Err, so nothing is lost.
Common mistakes
- Using a tuple as a lightweight struct. You get
.0and.1in the call sites and swapped-argument bugs. Name the fields. - Using
Vecfor data that never changes size. This is harmless but hides the invariant.[u8; 4]documents and enforces it, andVec<u8>does not. - Taking
Vec<T>by value in a read-only function. The caller must give up ownership or clone. Take&[T]. - Indexing with
[]on untrusted indices. An out-of-range index panics. Useget, which returnsNone. - Building huge arrays on the stack. A stack overflow aborts the program. Use
vec![0; n]. - Expecting different lengths to be the same type.
[i32; 3]does not coerce to[i32; 4]. Take a slice, or use const generics when the length must stay in the type.
Exercise
You are writing a function that computes the average of some numbers, and a caller has a [f64; 6], another has a Vec<f64>, and a third has the last three elements of a Vec<f64>. What should the parameter type be, and what should the return type be to handle an empty input?
Show answer
Take &[f64], which accepts &array, &vec, and &vec[vec.len() - 3..]. Return Option<f64>, with None for an empty slice, so the function does not divide by zero.
Exercise
For each case, name the best type: (a) a function returns a person's name and age, used once by the caller; (b) a chessboard with 8 rows and 8 columns; (c) lines read from a file; (d) an RGB color passed through many functions.
Show answer
(a) A tuple (String, u32), destructured at the call site. (b) [[Piece; 8]; 8], since the size is fixed by the rules of the game. (c) Vec<String>, since the line count is only known at run time. (d) A struct with r, g, b fields, or a type alias for [u8; 3] if the three values are always handled as a group. A struct is preferable because it names the fields.