Sub topic 10
Compound types: tuples and arrays
This chapter assumes you can write let bindings, use mut, and read the integer and float types from earlier chapters. It also assumes you can run a program with cargo run or rustc. Here you will learn how Rust groups several values into one, and how tuples and arrays differ in type, size, and use.
Two ways to group values
Rust has two built-in compound types for grouping values:
- A tuple holds a fixed number of values. The values can have different types.
- An array holds a fixed number of values. All values must have the same type.
Both have a size known at compile time, and neither can grow or shrink. For a collection that can grow, you need Vec<T>, which later chapters cover. Because their size is fixed, tuples and arrays can live directly on the stack with no heap allocation.
| Property | Tuple | Array |
|---|---|---|
| Element types | May differ | Must be identical |
| Type notation | `(i32, f64, char)` | `[i32; 3]` |
| Access syntax | `t.0`, `t.1` | `a[0]`, `a[1]` |
| Index | Constant position in the source | Any `usize` expression |
| Length in the type | Yes, as the number of types listed | Yes, as the `N` in `[T; N]` |
| Can be looped over | No | Yes |
Tuples
Creating and reading tuples
A tuple is written as a comma-separated list in parentheses. The type is the list of element types in the same order.
fn main() {
let point: (i32, f64, char) = (10, 2.5, 'z');
let (x, y, c) = point;
println!("{x} {y} {c} {}", point.0);
let months = [1, 2, 3];
let zeros = [0u8; 4];
println!("{} {}", months[0], zeros.len());
}The line let (x, y, c) = point; is destructuring. It is a pattern on the left side of let that splits the tuple into three bindings. You can also read one field by position with point.0. The position is a literal number in the source. point.i with a variable i does not compile, because each field may have a different type and the compiler must know which one you mean.
Destructuring in detail
Patterns can be nested. Use _ to ignore one value and .. to ignore all the remaining values.
fn main() {
let record = ("Ada", 36, (51.5, -0.12));
let (name, _, (lat, lon)) = record;
println!("{name} at {lat}, {lon}");
println!("{}", record.2.0);
let (first, ..) = record;
println!("{first}");
}The pattern must match the shape of the tuple. let (a, b) = record; is a compile error because record has three fields. Only .. can stand in for a variable number of fields.
Mutating tuples
A tuple follows the usual binding rules. If the binding is mut, you can assign to individual fields. Each field keeps its type.
fn main() {
let mut pair = (1, "one");
pair.0 = 2;
pair.1 = "two";
println!("{pair:?}");
// pair.0 = "two"; // error[E0308]: mismatched types
}With let pair = (1, "one");, any assignment to pair.0 is rejected, because immutability applies to the whole value.
Returning several values
Tuples are most often used to return more than one value from a function. The caller usually destructures the result at once.
fn min_max(values: [i32; 5]) -> (i32, i32) {
let mut min = values[0];
let mut max = values[0];
for &v in &values {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
(min, max)
}
fn main() {
let (lo, hi) = min_max([4, -2, 9, 0, 7]);
println!("{lo} {hi}");
}This prints -2 9. If a tuple grows past two or three fields, a struct with named fields is easier to read, because result.2 says nothing about what the third value means.
The unit type and one-element tuples
The empty tuple () is called the unit type. It has exactly one value, also written (). Rust uses it as the result of expressions that produce nothing useful. A function with no declared return type returns ().
A tuple with one element needs a trailing comma. Without the comma, the parentheses are only grouping.
fn main() {
let unit: () = ();
let one: (i32,) = (5,);
let just_int: i32 = (5);
println!("{unit:?} {one:?} {just_int}");
}This prints () (5,) 5. The compiler warns about the unnecessary parentheses on (5), but the code runs.
Printing and comparing tuples
Tuples implement Debug, so you format them with {:?}. They do not implement Display, so println!("{}", point) fails to compile. Tuples also implement comparison traits when every element does. Comparison is lexicographic: the first fields are compared, and the next fields are looked at only on a tie.
fn main() {
println!("{}", (1, "b") < (2, "a"));
println!("{}", (1, "b") < (1, "c"));
println!("{}", (3, 4.0) == (3, 4.0));
}All three lines print true. This makes tuples handy as sort keys. The standard library implements these traits for tuples up to 12 elements.
Arrays
Type and construction
An array's type is written [T; N], where T is the element type and N is the length. The length is part of the type. [i32; 3] and [i32; 4] are different types, so you cannot pass one where the other is expected.
There are two literal forms. You can list the elements, or you can repeat one value N times with [value; N].
fn main() {
let primes: [u32; 4] = [2, 3, 5, 7];
let zeros = [0u8; 4];
let mut grid = [[0i32; 3]; 2];
grid[1][2] = 9;
println!("{:?} {:?} {:?}", primes, zeros, grid);
println!("{}", primes.len());
let idx = 7;
println!("{:?}", primes.get(idx));
}The output is:
[2, 3, 5, 7] [0, 0, 0, 0] [[0, 0, 0], [0, 0, 9]]
4
NoneHere grid is an array of two arrays, each holding three i32 values. You index it as grid[row][column]. The call primes.get(idx) returns an Option<&u32>. It gives None instead of panicking when the index is out of range.
Indexing and bounds checks
Array indexes must be usize. Rust checks every index against the length.
- If the index is a constant the compiler can see, such as
primes[10]on a 4-element array, the build fails with an error from theunconditional_paniclint. - If the index is only known at run time, the check happens when the program runs. An out-of-range index panics and stops the thread.
fn main() {
let months = [1, 2, 3];
let i = std::env::args().count() + 5;
println!("{}", months[i]);
}Run with no arguments, i is 6, and the program panics with a message like index out of bounds: the len is 3 but the index is 6. Memory is never read past the end, which is one of the safety guarantees Rust gives you. Use .get(i) when an out-of-range index is an expected case rather than a bug.
Repeat expressions and non-Copy elements
The form [value; N] copies value into every slot. That requires the value's type to implement Copy, or the value to be a constant expression. So [String::new(); 3] does not compile, because String is not Copy. Use std::array::from_fn, which calls a closure once per index.
fn main() {
let names: [String; 3] = std::array::from_fn(|i| format!("item{i}"));
println!("{names:?}");
}This prints ["item0", "item1", "item2"].
Arrays are values
An array owns its elements inline. Assigning an array moves or copies the whole thing, depending on its element type. When the element type is Copy, the array is Copy too, and an assignment makes an independent duplicate.
fn main() {
let a = [1, 2, 3];
let mut b = a;
b[0] = 99;
println!("{:?} {:?}", a, b);
}This prints [1, 2, 3] [99, 2, 3]. Passing an array to a function copies it as well, which is expensive for a large array. Because the array lives on the stack, a very large one such as [0u8; 10_000_000] can overflow the stack. Functions normally take a reference or a slice instead.
Slices and iteration
A slice is a borrowed view of part of an array, written &[T]. You can create one from a range of indexes. Later chapters cover slices fully. For now, know that they let one function work with arrays of any length.
fn sum(values: &[i32]) -> i32 {
let mut total = 0;
for v in values {
total += v;
}
total
}
fn main() {
let a = [10, 20, 30, 40];
println!("{}", sum(&a));
println!("{}", sum(&a[1..3]));
for x in a {
print!("{x} ");
}
println!();
}The output is 100, then 50, then 10 20 30 40. In editions 2021 and later, for x in a iterates over the array by value. Arrays also compare with == when their elements do, and arrays of the same length compare lexicographically with <.
Choosing between them
Some common mistakes to avoid:
- Using a tuple for a homogeneous list.
(i32, i32, i32)cannot be looped over or indexed by a variable. An array can. - Using an array when the length is not known until run time. The length
Nmust be a constant expression, so[0; n]with a variablendoes not compile. - Expecting
[T; 3]to be accepted where[T; 4]is required. The length is part of the type. - Reading the third field of a tuple as
t.2everywhere in a large program. Name the fields with a struct once the meaning is not obvious.
Interaction with type inference
The compiler infers element types from literals and from use. With let months = [1, 2, 3]; the element type defaults to i32. If you later pass months to a function that takes [u8; 3], the literals are inferred as u8 instead. An annotation such as let a: [u16; 2] = [1, 2]; pins the type directly. A suffix on one literal, as in [0u8; 4], fixes the type for all elements.
Exercise
Why does let t = (1, 2.0, 'c'); let i = 1; println!("{}", t.i); fail to compile, while let a = [1, 2, 3]; let i = 1; println!("{}", a[i]); is accepted?
Show answer
Tuple fields can have different types, so the compiler must know at compile time which field you mean, and .i with a variable is not allowed. Array elements all share one type, so any usize expression works as an index. Its bounds are checked at run time.
Exercise
Write a function fn bounds(v: [f64; 3]) -> (f64, f64) that returns the smallest and largest values of the array as a tuple. Then give the output of let (lo, hi) = bounds([2.5, -1.0, 4.0]); println!("{lo} {hi}");.
Show answer
One solution: fn bounds(v: [f64; 3]) -> (f64, f64) { let mut lo = v[0]; let mut hi = v[0]; for &x in &v { if x < lo { lo = x; } if x > hi { hi = x; } } (lo, hi) }. The call prints -1 4, because f64 values print without a trailing .0 when formatted with {}.
Exercise
What do let a = [String::new(); 3]; and let b = [0u8; 3]; let c = b; do, and why do they differ?
Show answer
The first does not compile. A repeat expression needs a Copy element type (or a constant), and String is not Copy; std::array::from_fn is the fix. The second compiles, and b is still usable afterward, because [u8; 3] is Copy, so let c = b; copies the array rather than moving it.