Sub topic 7
Arrays: fixed-length sequences of one type
This chapter assumes you know Rust let bindings, functions, println!, scalar types such as i32 and u8, and basic borrowing with &. You should be able to run a program with cargo run.
What an array is
An array is a collection of values that all have the same type and a length fixed at compile time. Its type is written [T; N], where T is the element type and N is the number of elements.
fn main() {
let primes: [u32; 5] = [2, 3, 5, 7, 11];
let zeros = [0u8; 4];
println!("{} {}", primes.len(), zeros.len());
}The first line uses a literal with the elements listed in brackets. The second uses the repeat form [value; N], which fills the array with N copies of value. Here that gives [0, 0, 0, 0]. The compiler infers the type [u8; 4] from the literal.
The length is part of the type
[i32; 3] and [i32; 4] are different types. You cannot assign one to the other, and you cannot grow or shrink an array after you create it.
fn main() {
let a: [i32; 3] = [1, 2, 3];
let b: [i32; 4] = [1, 2, 3, 4];
// let c: [i32; 3] = b; // error: mismatched types
println!("{:?} {:?}", a, b);
}The {:?} format prints an array in debug form, for example [1, 2, 3].
Reading elements
Use an index starting at 0. An index must be a usize.
fn main() {
let primes = [2, 3, 5, 7, 11];
println!("{}", primes[0]);
println!("{:?}", primes.get(10));
}primes[0] returns the element. primes.get(10) returns an Option. It gives None here because index 10 is out of range. Indexing with [] panics when the index is out of range, so use get when the index comes from outside your program. The next chapters cover indexing in more detail.
Common mistakes
- Writing the wrong length in a type annotation.
let a: [i32; 3] = [1, 2];fails to compile because the literal has two elements. - Mixing element types.
[1, "two"]does not compile, because every element must have the same type. Use a tuple for mixed types. - Expecting to push onto an array. Arrays have no
push. If the length changes at run time, use aVec.
How arrays are copied
If the element type is Copy, the array is Copy too. Assigning it copies every element.
fn main() {
let a = [1, 2, 3];
let mut b = a;
b[0] = 99;
println!("{:?} {:?}", a, b);
}This prints [1, 2, 3] [99, 2, 3]. The array b is an independent copy, so changing it leaves a alone. Note that b needs mut because you change an element.
Exercise
Why does let a: [i32; 3] = [1, 2, 3, 4]; fail to compile, and how would you fix it?
Show answer
The type says the array has three elements, but the literal has four. The length is part of the type, so the two do not match. Fix it by changing the annotation to [i32; 4], removing one element, or dropping the annotation so the compiler infers [i32; 4].
Exercise
What does [7u8; 3] produce, and what is its type?
Show answer
It produces [7, 7, 7], and its type is [u8; 3].