Tuples group a few values of different types. Arrays hold a fixed number of values of one type, and the length is part of the type. A slice is a view into part of an array, so one function can take any length.
So far every variable has held one value: a number, a bool, a piece of text. This part covers the first ways to hold several. A tuple groups a few values of different types. An array holds a fixed number of values of one type. A slice is a view into part of an array.
We’ll also see what happens when you read past the end of an array, how to loop over one, and why functions usually take a slice instead of an array. It builds on the functions and loops from Part 3. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
This function adds up three scores. We call it with four. Decide what happens before you read on:
fn total(scores: [i32; 3]) -> i32 {
scores[0] + scores[1] + scores[2]
}
fn main() {
let scores = [90, 72, 85, 60];
println!("{}", total(scores));
}
It doesn’t add the first three and ignore the fourth. It doesn’t compile:
error[E0308]: mismatched types
--> src/main.rs:7:26
|
7 | println!("{}", total(scores));
| ----- ^^^^^^ expected an array with a size of 3, found one with a size of 4
| |
| arguments to this function are incorrect
[i32; 3] means “an array of exactly three i32 values”. The 3 is part of the type. An array of four is a different type, so the compiler refuses it, the same way it would refuse a bool where an i32 should go. By the end of this part we’ll fix total so it takes any number of scores.
Tuples: a few values of different types
A tuple is a fixed group of values, written in round brackets. Each value can have its own type:
fn main() {
let person = ("Ana", 34, true);
println!("name: {}", person.0);
println!("age: {}", person.1);
println!("member: {}", person.2);
println!("all of it: {person:?}");
let mut point = (0, 0);
point.0 = 5;
println!("point: {point:?}");
}
It prints:
name: Ana
age: 34
member: true
all of it: ("Ana", 34, true)
point: (5, 0)
The type of person is (&str, i32, bool): a piece of text, a number and a bool, in that order. You read each part by its position with a dot: .0 is the first, .1 the second. Positions start at 0.
{} can’t print a whole tuple, but {:?} can. The ? asks for the debug format, which Rust provides for tuples and arrays of printable things. We’ll use it a lot in this part.
A tuple’s size is fixed when you write it. You can change the parts of a mut tuple, as point.0 = 5 does, but you can’t add a fourth part to a three-part tuple.
Taking a tuple apart
Writing .0 and .1 everywhere gets hard to read. You can unpack a tuple into named variables in one let. This is called destructuring:
fn main() {
let person = ("Ana", 34, true);
let (name, age, member) = person;
println!("{name} is {age}, member: {member}");
let (_, age_again, _) = person;
println!("just the age: {age_again}");
}
It prints:
Ana is 34, member: true
just the age: 34
The pattern on the left has the same shape as the tuple on the right, so each name gets the value in its position. _ means “there’s a value here, and I don’t need it”.
Returning two values from a function
A function returns one value. When you need two, return a tuple:
fn divide(a: i32, b: i32) -> (i32, i32) {
(a / b, a % b)
}
fn main() {
let (quotient, remainder) = divide(17, 5);
println!("17 / 5 = {quotient} remainder {remainder}");
}
It prints:
17 / 5 = 3 remainder 2
The return type (i32, i32) says “two i32 values, together”. The caller destructures them straight into two names.
The empty tuple, ()
A tuple can have no parts at all. Its type is written (), and so is its only value. It’s called the unit type:
fn say_hi() {
println!("hi");
}
fn main() {
say_hi();
let nothing = ();
println!("{nothing:?}");
}
It prints:
hi
()
You’ve been using () since Part 1, and Part 3 gave it a name. A function with no -> return type, like say_hi or main, returns (). It means “this produced no useful value”. When the compiler says it “expected i32, found ()“, it means a block ended without giving a value, often because of a ; after the last expression. Part 3 showed that mistake.
One more detail: (5) is just the number 5 in brackets. A tuple with one part needs a comma: (5,). You’ll rarely need one.
Arrays: a fixed number of values of one type
An array holds several values of the same type, in square brackets:
fn main() {
let primes = [2, 3, 5, 7, 11];
println!("first: {}", primes[0]);
println!("last: {}", primes[4]);
println!("how many: {}", primes.len());
println!("all: {primes:?}");
let zeros = [0; 5];
println!("zeros: {zeros:?}");
let mut counts: [u8; 3] = [0; 3];
counts[1] = 9;
println!("counts: {counts:?}");
let size = std::mem::size_of::<[i32; 5]>();
println!("[i32; 5] takes {size} bytes");
}
It prints:
first: 2
last: 11
how many: 5
all: [2, 3, 5, 7, 11]
zeros: [0, 0, 0, 0, 0]
counts: [0, 9, 0]
[i32; 5] takes 20 bytes
A few things to notice:
- You read one item with
primes[0]. This is called indexing, and the number is the index. Indexes start at 0, so the last of five items isprimes[4]. [0; 5]means “the value 0, five times”. It’s the quick way to make an array of one repeated value.- The type of an array is written
[type; length].countsis[u8; 3]: threeu8values. The length must be known when the program compiles. You can’t make an array whose length comes from user input. len()gives the number of items.- An array is just its items, side by side, with nothing extra. Five
i32values take 5 × 4 = 20 bytes. A local array likeprimeslives on the stack, the way a locali32does. There’s no heap part. (Part 6 shows the stack and the heap.)
Because the length is part of the type, [i32; 3] and [i32; 4] are different types. That’s why the total function in “Try this first” refused four scores.
Arrays of Copy items are Copy too, so let b = a; copies every item and both names stay usable. Part 6 explains what Copy means. For a large array, keep in mind that the copy is real work: every item is copied.
Reading past the end
What happens when the index is too big? It depends on whether the compiler can see the number.
When the index is a constant, the compiler sees the problem and stops:
fn main() {
let arr = [10, 20, 30];
let i = 5;
println!("{}", arr[i]);
}
It prints:
error: this operation will panic at runtime
--> src/main.rs:4:20
|
4 | println!("{}", arr[i]);
| ^^^^^^ index out of bounds: the length is 3 but the index is 5
|
= note: `#[deny(unconditional_panic)]` on by default
This error has no E number. It comes from a lint, a check that’s set to “deny” by default, as the last line says. The compiler worked out that i is always 5, and that 5 is past the end of three items.
Most of the time, though, the index comes from somewhere the compiler can’t see in advance: a function parameter, a file, the user. Then the check happens while the program runs:
fn show(arr: [i32; 3], i: usize) {
println!("item {i} is {}", arr[i]);
}
fn main() {
let arr = [10, 20, 30];
show(arr, 1);
show(arr, 5);
println!("this line never runs");
}
It prints:
item 1 is 20
panicked at src/main.rs:2:32:
index out of bounds: the len is 3 but the index is 5
Inside show, i could be any number, so the compiler can’t reject it. Instead, Rust checks every index against the length while the program runs. When the check fails, the program panics: it prints a message and stops. The last line never runs.
The real first line of a panic starts with thread 'main' and a number that changes from run to run, so we’ve left that part out. Read the panic in two lines:
panicked at src/main.rs:2:32is the file, line and column where it happened. Line 2 isarr[i]insideshow.the len is 3 but the index is 5says exactly what went wrong.
A panic is abrupt, but it’s safe. In C, arr[5] on a three-item array quietly reads whatever memory sits after it, a common source of security bugs. Rust stops instead.
Indexes have the type usize, an unsigned integer as wide as a memory address, so show takes i: usize. To read an item that might not be there without panicking, use .get(i). It returns an Option, which Part 11 covers.
Looping over an array
To visit every item, loop over the array with for:
fn main() {
let temps = [18, 21, 25, 19];
for t in temps {
println!("{t} degrees");
}
for (i, t) in temps.iter().enumerate() {
println!("day {i}: {t}");
}
}
It prints:
18 degrees
21 degrees
25 degrees
19 degrees
day 0: 18
day 1: 21
day 2: 25
day 3: 19
for t in temps gives you each item in turn, from first to last. You don’t touch an index at all, so you can’t get one wrong.
When you also want the position, use temps.iter().enumerate(). Read it left to right:
.iter()walks over the items of the array, one at a time..enumerate()pairs each item with a count that starts at 0.
Each pair is a tuple, (index, item), and the for destructures it into i and t, the same way let (a, b) = ... does. One small difference: through .iter(), t is a reference to the item rather than a copy of it. Part 7 explains references. println! prints it the same way, so here it doesn’t matter. Part 17 covers iter and its relatives properly.
Arrays of arrays
An array’s items can be arrays. That gives you a grid:
fn main() {
let mut grid = [[0; 3]; 2];
grid[0][1] = 5;
grid[1][2] = 7;
for row in grid {
for cell in row {
print!("{cell:3}");
}
println!();
}
println!("rows: {}, columns: {}", grid.len(), grid[0].len());
let size = std::mem::size_of::<[[i32; 3]; 2]>();
println!("{size} bytes");
}
It prints:
0 5 0
0 0 7
rows: 2, columns: 3
24 bytes
Read [[0; 3]; 2] from the inside out: [0; 3] is a row of three zeros, and [...; 2] is two of those rows. Its type is [[i32; 3]; 2]. grid[1][2] picks row 1, then column 2 inside it.
In memory there are no separate rows. The six numbers sit one after another, row 0 and then row 1, 6 × 4 = 24 bytes. print! is println! without the newline at the end, which is why each row stays on one line.
A first look at slices
Often you want only part of an array: the first three items, or everything after the first. A slice gives you that without copying anything:
fn main() {
let arr = [10, 20, 30, 40, 50];
let middle = &arr[1..4];
println!("middle: {middle:?}, {} items", middle.len());
println!("first two: {:?}", &arr[..2]);
println!("from index 3: {:?}", &arr[3..]);
println!("all of it: {:?}", &arr[..]);
println!("1 to 3 inclusive: {:?}", &arr[1..=3]);
println!("middle[0] is arr[1]: {}", std::ptr::eq(&middle[0], &arr[1]));
println!("array: {} bytes", std::mem::size_of::<[i32; 5]>());
println!("slice: {} bytes", std::mem::size_of::<&[i32]>());
}
It prints:
middle: [20, 30, 40], 3 items
first two: [10, 20]
from index 3: [40, 50]
all of it: [10, 20, 30, 40, 50]
1 to 3 inclusive: [20, 30, 40]
middle[0] is arr[1]: true
array: 20 bytes
slice: 16 bytes
1..4 is a range: it starts at 1 and stops before 4, so it covers indexes 1, 2 and 3. That’s three items. You can leave out the start (..2, from the beginning), the end (3.., to the end), or both (.., everything). 1..=3 includes the end.
&arr[1..4] has the type &[i32]: “a slice of i32 values”. Notice what’s missing: the length. A slice can cover three items, or five, or none, and the type is the same. That’s what makes slices useful.
The & in front means “a view into”, and it’s the subject of Part 7. For now, read &arr[1..4] as “a view of items 1 to 3 of arr, not a copy”. The std::ptr::eq line proves it: the first item of middle is the very same piece of memory as arr[1].
So what is a slice, if it isn’t a copy? It’s two numbers: a pointer to its first item, and how many items it covers. That’s the 16 bytes on a 64-bit machine, 8 for the pointer and 8 for the length. The 20 bytes of numbers stay where they are, inside arr.
A slice is a pointer and a length. &arr[1..4] points at arr[1] and says “3 items”, so it sees 20, 30 and 40 without copying them.
The dashed blue arrow is how this series draws a & view. A solid arrow, as in Part 6, means “owns”. The slice doesn’t own the numbers. arr does.
Slices let one function take any length
Now we can fix total from “Try this first”. Instead of [i32; 3], the parameter takes &[i32], a slice of any length:
fn total(scores: &[i32]) -> i32 {
let mut sum = 0;
for s in scores {
sum += s;
}
sum
}
fn main() {
let three = [90, 72, 85];
let four = [90, 72, 85, 60];
println!("three: {}", total(&three));
println!("four: {}", total(&four));
println!("first two of four: {}", total(&four[..2]));
println!("none: {}", total(&[]));
}
It prints:
three: 247
four: 307
first two of four: 162
none: 0
One function now handles three scores, four scores, part of an array, and an empty list. &three is a view of the whole array, and Rust turns it into a &[i32] for you when the function asks for one. &four[..2] passes a view of only the first two items.
for s in scores loops over a slice the same way as over an array. Each s is a reference to an item, and sum += s reads the number through it.
This is the usual shape in real Rust code. A function that only needs to read a list of items takes a slice, so it doesn’t care how long the list is or where it came from. In Part 13 you’ll see that a Vec, Rust’s growable list, hands out slices the same way.
Worked example: an off-by-one panic
Here’s a function that should return the last reading from a sensor. It has a bug that people coming from other languages write often:
fn last(readings: &[i32]) -> i32 {
readings[readings.len()]
}
fn main() {
let readings = [12, 15, 11];
println!("last reading: {}", last(&readings));
}
It prints:
panicked at src/main.rs:2:5:
index out of bounds: the len is 3 but the index is 3
Read it the way we read the panic above:
src/main.rs:2:5points at line 2,readings[readings.len()].- “the len is 3 but the index is 3”: the slice has three items, at indexes 0, 1 and 2. Index 3 is one past the end.
The fix is readings.len() - 1. But that has a trap of its own. If the slice is empty, len() is 0, and 0 - 1 doesn’t fit in a usize:
fn last(readings: &[i32]) -> i32 {
readings[readings.len() - 1]
}
fn main() {
println!("last reading: {}", last(&[12, 15, 11]));
println!("last reading: {}", last(&[]));
}
It prints:
last reading: 11
panicked at src/main.rs:2:14:
attempt to subtract with overflow
That’s the overflow panic from Part 2. A function that takes a slice has to decide what an empty one means. Here the caller checks first, and is_empty() makes that easy:
fn last(readings: &[i32]) -> i32 {
readings[readings.len() - 1]
}
fn report(readings: &[i32]) {
if readings.is_empty() {
println!("no readings yet");
} else {
println!("last of {readings:?}: {}", last(readings));
}
}
fn main() {
report(&[12, 15, 11]);
report(&[7]);
report(&[]);
}
It prints:
last of [12, 15, 11]: 11
last of [7]: 7
no readings yet
report checks before it calls last, so last never sees an empty slice. Part 11 shows a cleaner design, where last itself returns “nothing” for an empty slice instead of panicking.
Worked example: a week of temperatures
Let’s put tuples, arrays and slices together. We have a week of temperatures and the names of the days. We want the coldest and warmest day of the whole week, and of the weekend alone.
fn coldest_and_warmest(temps: &[i32]) -> (usize, usize) {
let mut cold = 0;
let mut warm = 0;
for (i, t) in temps.iter().enumerate() {
if *t < temps[cold] {
cold = i;
}
if *t > temps[warm] {
warm = i;
}
}
(cold, warm)
}
fn main() {
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let temps = [18, 21, 25, 19, 16, 23, 20];
let (cold, warm) = coldest_and_warmest(&temps);
println!("week: coldest {} ({})", days[cold], temps[cold]);
println!("week: warmest {} ({})", days[warm], temps[warm]);
let weekend = &temps[5..];
let (cold, warm) = coldest_and_warmest(weekend);
println!("weekend: coldest {} ({})", days[5 + cold], weekend[cold]);
println!("weekend: warmest {} ({})", days[5 + warm], weekend[warm]);
}
It prints:
week: coldest Fri (16)
week: warmest Wed (25)
weekend: coldest Sun (20)
weekend: warmest Sat (23)
Walk through it:
coldest_and_warmesttakes a slice, so the same function works for all seven days and for the two-day weekend.- It returns a tuple of two indexes, and
maindestructures it intocoldandwarm. .iter().enumerate()gives each temperature with its index.tis a reference to the item, so*treads the number it points at. Part 7 explains the*. Without it, Rust won’t compare a reference with a number.- The indexes are positions in the slice, not in the array. In
weekend, index 0 is Saturday, which is index 5 intemps. That’s why the second line adds 5 before looking up the day name. A slice starts counting from 0 wherever it begins.
That last point is worth remembering. A slice knows where it starts in memory, but not where it started in the array it came from.
Tips and traps
(5)is not a tuple. It’s 5 in brackets. A one-item tuple needs a trailing comma,(5,). If the compiler says “expected(i32,), found integer”, look for the missing comma.- The end of a range is left out.
&arr[1..3]is two items, indexes 1 and 2. Use1..=3when you want the end included. Most off-by-one bugs with slices come from this. - A bad slice range panics too, and the compiler doesn’t catch it.
&arr[2..7]on a five-item array compiles, even with constants, and then panics with “range end index 7 out of range for slice of length 5”. Only plain constant indexes likearr[5]are caught at compile time. for i in 0..arr.len()gets a clippy warning. It works, but clippy, Rust’s linter, reportsneedless_range_loop. Loop over the items withfor x in arr, or use.iter().enumerate()when you need the index too.- A function that takes
[i32; 3]only takes three. The length is part of the type, so[i32; 4]is a mismatch (E0308). Take&[i32]instead and pass&arr. - Indexes are
usize. If you have ani32and tryarr[n], the compiler says the array “cannot be indexed byi32” (E0277). Store indexes asusizefrom the start, or convert withas usizeonce you know the number isn’t negative.
An array owns a fixed number of values; a slice is a pointer and a length that lets you look at some of them.
Exercises
Exercise 1. Write a function swap that takes a tuple (i32, char) and returns a tuple (char, i32) with the two parts the other way round. Call it with (7, 'x') and print the result with {:?}.
Exercise 2. Write fn largest(nums: &[i32]) -> i32 that returns the largest number in a slice. You can assume the slice isn’t empty. Call it on the array [3, 9, 2, 7], then on a slice of only its last two items.
Exercise 3. Without running it, work out the four lines this prints:
let grid = [[1, 2, 3], [4, 5, 6]];
println!("{}", grid[1][0]);
println!("{}", grid.len());
println!("{}", grid[0].len());
println!("{:?}", &grid[1][1..]);
Answers
1. Destructure the tuple, then build a new one in the other order:
fn swap(pair: (i32, char)) -> (char, i32) {
let (n, c) = pair;
(c, n)
}
fn main() {
println!("{:?}", swap((7, 'x')));
}
It prints:
('x', 7)
You can also write the body as (pair.1, pair.0). Both do the same thing.
2. Start with the first item as the best so far, then compare every item with it:
fn largest(nums: &[i32]) -> i32 {
let mut best = nums[0];
for n in nums {
if *n > best {
best = *n;
}
}
best
}
fn main() {
let nums = [3, 9, 2, 7];
println!("largest of all: {}", largest(&nums));
println!("largest of the last two: {}", largest(&nums[2..]));
}
It prints:
largest of all: 9
largest of the last two: 7
nums[0] panics on an empty slice, which is why the exercise lets you assume it isn’t empty.
3. grid[1] is the second row, [4, 5, 6], so grid[1][0] is 4. The grid has 2 rows, and each row has 3 items. &grid[1][1..] is a slice of the second row from index 1 to the end:
fn main() {
let grid = [[1, 2, 3], [4, 5, 6]];
println!("{}", grid[1][0]);
println!("{}", grid.len());
println!("{}", grid[0].len());
println!("{:?}", &grid[1][1..]);
}
It prints:
4
2
3
[5, 6]
What’s next
A string is a sequence of bytes, and &str is a slice of them, much like the &[i32] we built here. In Part 5, we’ll see why that makes text in Rust trickier than numbers, and why s[0] doesn’t compile.