Sub topic 10
Compound types: tuples and arrays
This chapter assumes you can read basic Rust, know how let and mut work, and know the scalar types (integers, floats, bool, char). A compound type groups several values into one. Rust has two built-in compound types for this: tuples and arrays.
Tuples
A tuple is a fixed-length group of values. The values can have different types. The type is written as a list in parentheses, such as (i32, f64, char). The length and the type of each position are part of the tuple's type, so (i32, f64) and (i32, f64, char) are different types.
You can read a tuple in two ways: destructuring or position access.
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 binds three new names in one statement. The expression point.0 reads the first field by position. The index after the dot is a literal number, not a variable, so you cannot loop over a tuple with point.i.
The empty tuple () is called the unit type. A function that returns no value returns ().
Arrays
An array holds a fixed number of values that all have the same type. Its type is written [T; N], where T is the element type and N is the length. The length is part of the type, so [i32; 3] and [i32; 4] are different types.
There are two ways to write an array:
- A list of values:
[1, 2, 3]. - A repeat expression:
[0u8; 4], which makes four copies of0u8.
The example above uses both. months has type [i32; 3] and zeros has type [u8; 4]. The len method returns the length.
Arrays live on the stack by default, and their size must be known at compile time. If you need a collection that grows, use Vec<T>, which a later chapter covers.
Indexing and bounds checks
You read an element with months[0]. Indexes start at 0 and have type usize. Rust checks every index at run time. If the index is out of range, the program panics instead of reading unrelated memory.
fn main() {
let months = [1, 2, 3];
let i = months.len();
println!("{}", months[i]); // panics: index out of bounds
}If the index is a constant the compiler can see, such as months[5], the compiler may reject the program at compile time. When the index comes from a variable, the check happens at run time.
Tuples compared with arrays
| Feature | Tuple | Array |
|---|---|---|
| Element types | May differ | All the same |
| Type notation | `(i32, f64)` | `[i32; 3]` |
| Access | `t.0`, destructuring | `a[0]`, destructuring |
| Index can be a variable | No | Yes |
| Can be looped over | No | Yes |
Choose a tuple when the positions mean different things, such as a pair of a name and an age. Choose an array when the values are the same kind of thing and you want to process them in a loop.
Mutability and compound types
Mutability applies to the whole binding. To change one element, declare the binding with mut.
fn main() {
let mut pair = (1, "one");
pair.0 = 2;
let mut grid = [0; 3];
grid[1] = 7;
println!("{:?} {:?}", pair, grid);
}This prints (2, "one") [0, 7, 0]. Without mut, both assignments fail with error E0594. You cannot make only one field of a tuple mutable.
Common errors
- Wrong length in a type annotation.
let a: [i32; 3] = [1, 2];fails because the lengths differ. - Mixed element types in an array.
[1, "two"]fails because an array needs one element type. - Using a variable as a tuple index.
t.iis an error. Use an array or amatchinstead. - Using a signed index.
months[i]needsito beusize. Ani32index is a type error, and you must convert it first. - Destructuring with the wrong count.
let (a, b) = (1, 2, 3);fails. Use_for values you want to skip, as inlet (a, _, _) = (1, 2, 3);.
Exercise
What are the types of let a = [1u8; 5]; and let t = (1u8, 5usize);, and which one can you index with a loop variable?
Show answer
a has type [u8; 5] and t has type (u8, usize). Only the array can be indexed with a loop variable, as in a[i] with i: usize. Tuple fields need a literal position such as t.0.
Exercise
What happens when you run let v = [10, 20, 30]; let i = 3; println!("{}", v[i]);?
Show answer
The program compiles but panics at run time with an "index out of bounds" message, because valid indexes are 0 to 2.