Sub topic 8
Initializing arrays with repeated values
This chapter assumes you know let bindings, scalar types such as i32 and bool, and the idea that Copy types are duplicated on assignment. You also need to be able to run programs with cargo.
The repeat expression
A literal like [1, 2, 3] lists every element. When you need many identical elements, write [value; N]. The value comes first, then a semicolon, then the length.
fn main() {
let zeros = [0u8; 4];
let flags = [false; 3];
let grid = [[0i32; 3]; 2];
println!("{:?} {:?} {:?}", zeros, flags, grid);
}This prints [0, 0, 0, 0] [false, false, false] [[0, 0, 0], [0, 0, 0]]. The last line shows that the repeated value can itself be an array. That gives you a two-row, three-column grid.
The type of [0u8; 4] is [u8; 4]. The length is part of the type, so it must be known at compile time.
The length must be a constant
N must be a usize that the compiler can compute. A const works. A runtime variable does not.
const SIZE: usize = 4;
fn main() {
let buffer = [0u8; SIZE];
println!("{}", buffer.len());
}Writing let n = 4; let a = [0u8; n]; is a compile error, because n is a variable and not a constant. If you need a length chosen at runtime, use a Vec, covered in a later chapter.
Non-Copy values
Repeating a value means copying it into every slot. By default, the compiler therefore requires the value to implement Copy. A String or Vec does not, so this fails:
// Does not compile: String is not Copy
let names = [String::new(); 3];There are two common fixes.
- Use
std::array::from_fn. It calls a closure once per index, so each element is built separately. - Use an inline
constblock, which repeats a constant expression and builds a fresh value in each slot. This needs Rust 1.79 or later.
fn main() {
let names: [String; 3] = std::array::from_fn(|i| format!("item{i}"));
println!("{:?}", names);
let lists: [Vec<i32>; 2] = [const { Vec::new() }; 2];
println!("{:?}", lists);
}The first line prints ["item0", "item1", "item2"]. The second prints [[], []]. Use from_fn when each element should differ, such as depending on its index. Use the const block when every element is the same empty value.
Choosing an initializer
Exercise
Why does let v = vec![1, 2]; let a = [v; 3]; fail to compile, and how would you build an array of three empty Vec<i32> values instead?
Show answer
Vec<i32> is not Copy, so [v; 3] cannot duplicate it into three slots. Build the array with [const { Vec::new() }; 3] (Rust 1.79+) or with std::array::from_fn(|_| Vec::new()).