Sub topic 7
Arrays: fixed-length sequences of one type
This chapter assumes you can write basic Rust functions, know the scalar types (i32, f64, bool, char), understand & borrowing, and can run programs with cargo. It covers what an array is and how its type works. Indexing, iteration, slices, and Vec get their own chapters.
What an array is
An array is a sequence of values with two fixed properties:
- Every element has the same type.
- The number of elements is known at compile time and never changes.
The type is written [T; N]. T is the element type. N is the length, a constant expression of type usize. A literal lists the elements in square brackets.
use std::mem::size_of;
fn main() {
let days: [&str; 3] = ["Mon", "Tue", "Wed"];
let primes = [2, 3, 5, 7]; // inferred as [i32; 4]
let flags: [bool; 0] = [];
println!("{} {} {}", days.len(), primes.len(), flags.len());
println!("{:?}", primes);
println!("{}", size_of::<[u32; 5]>());
println!("{}", size_of::<[u8; 0]>());
}This prints 3 4 0, then [2, 3, 5, 7], then 20, then 0. Five u32 values take 5 × 4 = 20 bytes. An empty array takes no space.
The compiler infers both the element type and the length from the literal. You only need an annotation when you want a different element type than the default. For example, [1, 2, 3] is [i32; 3], but let a: [u8; 3] = [1, 2, 3]; makes it [u8; 3].
The length is part of the type
In Rust, [i32; 3] and [i32; 4] are different types. They are as unrelated as i32 and String. Many beginners expect an array's length to be a runtime property, as in other languages, and that expectation causes most early array errors.
If you write the following, the compiler rejects it:
let a: [i32; 3] = [1, 2, 3, 4];
error[E0308]: mismatched types
expected an array with a size of 3, found one with a size of 4The check happens before the program runs. A function that takes [i32; 3] will not accept any other length:
fn total(values: [i32; 3]) -> i32 {
values.iter().sum()
}
fn main() {
println!("{}", total([1, 2, 3]));
}Calling total([1, 2, 3, 4]) would fail to compile. If you want one function to accept arrays of any length, you need slices (a later chapter) or const generics (also later).
The length must be a compile-time constant
The N in [T; N] cannot come from a variable computed at runtime. A const item works. A plain let binding does not, even when its value looks obvious.
const SIZE: usize = 4;
fn main() {
let buffer = [0u8; SIZE];
println!("{}", buffer.len());
}This prints 4. The form [value; SIZE] repeats a value, and it is covered in the next chapter. If the length is only known while the program runs, such as the number of lines in a file, use a Vec.
Arrays are values, not references
An array owns its elements, and it stores them inline. A local array lives on the stack, in one contiguous block. There is no pointer or length field stored next to it. The length lives only in the type.
This has a consequence for assignment and function calls. An array is Copy whenever its element type is Copy. Otherwise assignment moves it.
fn total(values: [i32; 3]) -> i32 {
values.iter().sum()
}
fn main() {
let a = [1, 2, 3];
let b = a; // copies, because i32 is Copy
println!("{} {}", total(a), total(b));
println!("{}", a == b);
let names = [String::from("Ada"), String::from("Grace")];
let moved = names; // moves, because String is not Copy
println!("{:?}", moved);
// Using `names` here would be a compile error: value moved.
}The output is 6 6, then true, then ["Ada", "Grace"]. Both a and b stay usable. Passing a to total copies all three integers.
Copying is cheap for three integers, but it is not free for large arrays. An array of 100,000 u64 values holds 800,000 bytes, and every by-value pass copies all of them. For large arrays, pass a reference (&[u64; 100_000]) or a slice. Large local arrays can also overflow the stack, which is typically a few megabytes on the main thread. If you need a big buffer, use a Vec or a Box.
Traits arrays implement
Arrays of any length implement the traits you would expect, as long as the element type does:
| Trait | Condition | What it gives you |
|---|---|---|
| `Debug` | `T: Debug` | `{:?}` printing |
| `Clone` and `Copy` | `T: Clone` / `T: Copy` | `.clone()` and implicit copies |
| `PartialEq` and `Eq` | `T: PartialEq` / `T: Eq` | `==` and `!=` between arrays of the same type |
| `PartialOrd` and `Ord` | `T: PartialOrd` / `T: Ord` | Lexicographic comparison with `<` and `>` |
| `Hash` | `T: Hash` | Use as a `HashMap` key |
| `Default` | `T: Default` | `Default::default()` fills every slot |
Equality compares element by element, so it only works between arrays of the same type. Comparing [i32; 3] with [i32; 4] using == does not compile.
fn main() {
let zeros: [i32; 4] = Default::default();
println!("{:?}", zeros);
println!("{}", [1, 2, 3] < [1, 2, 4]);
println!("{}", [1, 2, 3] == [1, 2, 3]);
}This prints [0, 0, 0, 0], then true, then true.
Common errors
- Mixed element types.
[1, "two", 3.0]does not compile. Every element must have one type. If you need to mix types, use a tuple (covered in earlier chapters) or anenum. - Mismatched lengths. Annotating
[i32; 5]and writing four elements is an error. Let the compiler infer the type when you can. - Runtime length.
let n = 3; let a = [0; n];fails becausenis not a constant. Useconst n: usize = 3;or aVec. - Use after move. Arrays of
Stringor other non-Copytypes move on assignment. Borrow with&nameswhen you want to keep using the original. - Oversized stack arrays. A very large array literal can crash with a stack overflow instead of a compile error. Switch to
Vecbefore that happens.
Exercise
Given let a = [1, 2, 3]; and let b = [1, 2, 3, 4];, what are their types, can you compare them with a == b, and what happens to a after let c = a;?
Show answer
a is [i32; 3] and b is [i32; 4]. They are different types, so a == b does not compile. After let c = a;, a is still usable, because [i32; 3] is Copy when its elements are Copy, so the assignment copies the three integers.
Exercise
Why does let n = 5; let grid = [0; n]; fail to compile, and what are two ways to fix it?
Show answer
The length of an array must be a compile-time constant, and a let binding is not one. Fix it by declaring const N: usize = 5; and writing [0; N], or by using a Vec such as vec![0; n] when the length is only known at runtime.