Sub topic 18
Choosing the right type
This chapter assumes you have read the earlier chapters on tuples, arrays, slices, and Vec. You should be comfortable with borrowing and with running programs using cargo. Here you will pick between the four types for a given problem.
Four questions
Ask these in order.
- Are the values the same type? If not, you need a tuple (or a struct).
- Is the length known at compile time and fixed? If so, use an array.
- Does a function only need to read or modify existing elements? If so, take a slice.
- Does the collection need to grow, shrink, or be sized at runtime? If so, use a
Vec.
Typical uses
| Type | Typical use | Length |
|---|---|---|
| Tuple | A pair or triple of related results, such as `(min, max)` | Fixed, part of the type |
| Array | Lookup tables, RGB channels, a chessboard row | Fixed, part of the type |
| Slice | Function parameters that read a sequence | Known at runtime |
| `Vec` | Data read from a file or built in a loop | Grows at runtime |
Tuples and arrays are stored inline, on the stack when they are local variables. A Vec keeps its elements on the heap. For small fixed data, an array avoids an allocation.
All four together
fn largest(values: &[i32]) -> Option<i32> {
values.iter().copied().max()
}
fn main() {
let reading: (&str, f64) = ("temp", 21.5);
let temps: [i32; 3] = [18, 21, 19];
let mut scores = vec![72, 95];
scores.push(88);
println!("{} {}", reading.0, reading.1);
println!("{:?}", largest(&temps));
println!("{:?}", largest(&scores));
println!("{:?}", largest(&scores[..2]));
}The tuple holds a &str and an f64, so an array could not hold it. temps has a fixed length. scores grows with push. largest takes &[i32], so it accepts the array, the Vec, and part of the Vec.
Common mistakes
- Using a tuple with many fields. Once you pass around
(String, u32, bool, f64), the positions.0to.3stop being readable. Use a struct with named fields. - Using a
Vecfor data that never changes size. An array states that intent and lets the compiler check it. - Taking
&Vec<T>or&[T; N]as a parameter. Take&[T]unless you need Vec-specific methods or a specific length. - Returning a slice of a local array. The array is dropped when the function ends, so return the array itself or a
Vec.
Exercise
You are writing a function that reads a list of temperature readings whose count is only known at runtime, and returns both the lowest and highest. Which types would you use for the parameter, the return value, and the place where the readings are stored?
Show answer
Store the readings in a Vec<f64>, since the count is only known at runtime. Take the parameter as &[f64] so callers can pass a Vec, an array, or a sub-range. Return Option<(f64, f64)>, a tuple of two values of the same type used as a pair. Option covers the empty case.