Sub topic 8
Initializing arrays with repeated values
This chapter assumes you can read basic Rust, know that an array type is written [T; N], and can run programs with cargo. It covers the [value; N] syntax, the rules for which values it accepts, and what to use when it refuses your element type.
The repeat expression
An array literal lists every element: [1, 2, 3]. When all elements are the same, the repeat expression is shorter. It has two parts separated by a semicolon: the value and the length.
fn main() {
let zeros = [0u8; 4];
let flags: [bool; 3] = [false; 3];
let names = ["n/a"; 2];
let unknown = [0; 5];
println!("{zeros:?} {flags:?} {names:?} {unknown:?}");
}This prints [0, 0, 0, 0] [false, false, false] ["n/a", "n/a"] [0, 0, 0, 0, 0].
Three details matter here:
- The type of the array is
[T; N], whereTis the type of the value andNis the length.[0u8; 4]is a[u8; 4]. - Type inference works as it does elsewhere.
[0; 5]with no annotation or other constraint becomes[i32; 5], becausei32is the default integer type. - The length is part of the type.
[0; 4]and[0; 5]are different types and cannot be assigned to each other.
The length must be a constant
The length N must be known at compile time. A literal, a const item, or a constant expression is accepted. A let binding is not, even if it never changes.
const SIZE: usize = 3;
fn main() {
let row = [1.5f64; SIZE];
let grid = [[0i32; SIZE]; 2];
println!("{row:?}");
println!("{grid:?}");
}This prints [1.5, 1.5, 1.5] and then [[0, 0, 0], [0, 0, 0]].
If you write let n = 3; let a = [0; n];, the compiler reports that attempting to use a non-constant value in a constant. When the size is only known at run time, you need a Vec, which a later chapter covers.
The length must also have type usize. A constant like const SIZE: i32 = 3 fails to compile in this position.
What the value must be
The value is evaluated once, and then the array is filled with copies of it. For that reason, the value must be one of the following:
- A type that implements
Copy, such as integers, floats,bool,char, references, and tuples or arrays ofCopytypes. - A path to a
constitem. - An inline
const { ... }block. This form is stable since Rust 1.79.
String and Vec<T> are not Copy, so this fails:
fn main() {
let names = [String::new(); 3];
println!("{names:?}");
}The error says the trait bound String: Copy is not satisfied. Rust refuses because there is no single value to duplicate bit for bit. Each String owns its own heap allocation, so each slot needs its own value.
Getting independent non-Copy elements
You have four options. Each produces a separate value in every slot.
fn main() {
const EMPTY: Vec<i32> = Vec::new();
let mut buckets = [EMPTY; 3];
buckets[0].push(1);
buckets[2].push(9);
println!("{buckets:?}");
let mut inline = [const { String::new() }; 2];
inline[1].push_str("hi");
println!("{inline:?}");
let squares: [usize; 5] = std::array::from_fn(|i| i * i);
println!("{squares:?}");
let defaults: [String; 3] = Default::default();
println!("{defaults:?}");
}The output is:
[[1], [], [9]]
["", "hi"]
[0, 1, 4, 9, 16]
["", "", ""]How each one works:
- A
constitem. Using a constant in a repeat expression evaluates it once per slot, so every slot gets a freshVec::new(). Changingbuckets[0]does not affectbuckets[1]. - An inline
constblock. This does the same without naming a separate item. It needs Rust 1.79 or newer. std::array::from_fn. It calls a closure once per index and builds the array from the results. Use it when each element depends on its position, or when the value is not a constant. The length comes from the type annotation, or from a turbofish such asfrom_fn::<_, 5, _>.Default::default(). The standard library implementsDefaultfor arrays of lengths 0 to 32 when the element type implementsDefault. Beyond length 32 this does not work.
Nested repeats are copies, not shared rows
Because [i32; 3] is Copy, you can repeat an array inside an array. Beginners from other languages sometimes worry that all rows are one shared object. They are not.
fn main() {
let mut grid = [[0; 3]; 2];
grid[0][1] = 7;
println!("{grid:?}");
}This prints [[0, 7, 0], [0, 0, 0]]. Each row is its own copy, so only row 0 changed. Read the type from the inside out: [[0; 3]; 2] is 2 rows, each of 3 columns, so grid[row][col].
Size and the stack
Arrays live inline where they are declared, which for a local variable means the stack. A repeat expression with a large length can therefore overflow the stack at run time.
A zero-length repeat like [x; 0] is valid and produces an empty array. The value x is still evaluated and then dropped, so any side effects in the expression still happen.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `the trait bound String: Copy is not satisfied` | Repeating a non-`Copy` value | Use a `const` item, an inline `const` block, `from_fn`, or `Default` |
| Attempting to use a non-constant value in a constant | Length comes from a `let` binding | Use a `const`, or switch to `Vec` |
| Mismatched types, expected `usize` | Length constant has another integer type | Declare the constant as `usize` |
| `Default` not implemented for `[T; 64]` | Array longer than 32 | Use `from_fn` or a repeat expression |
| Stack overflow at run time | Very large local array | Use `Vec` or `Box` |
Exercise
You need an array of 4 empty Vec<u8> values, and later you will push different bytes into each one. [Vec::new(); 4] does not compile. Write one initialization that works, and say why it works.
Show answer
Use const EMPTY: Vec<u8> = Vec::new(); let mut a = [EMPTY; 4];, or let mut a = [const { Vec::new() }; 4]; on Rust 1.79 or newer. Another option is std::array::from_fn(|_| Vec::new()) with a annotated as [Vec<u8>; 4]. These work because a constant is evaluated once per slot, and from_fn calls its closure once per slot. Each slot gets its own Vec, so pushing to one does not affect the others. [Vec::new(); 4] fails because Vec<u8> is not Copy.
Exercise
What is the type of let t = [[1u8; 4]; 3];, and what does t[2][3] refer to?
Show answer
The type is [[u8; 4]; 3], which is 3 rows of 4 u8 values. t[2][3] is the last element of the last row. Valid indices are 0..=2 for the first index and 0..=3 for the second.