Arrays
An array [T; N] is N values of type T stored inline. N is part of the type, so [u8; 4] and [u8; 16] are different types.
Detailed Explanation
let rgb: [u8; 3] = [12, 80, 210]; is three bytes, usually on the stack if the array is a local. There is no heap allocation and no capacity. The length cannot change. [T; N] implements Copy when T does, so assignment copies every element.
Because N is a type parameter (a const generic), a function that takes [u8; 4] will not accept [u8; 16]. The function that accepts both takes a slice, &[u8]. Arrays coerce to slices: fn f(xs: &[u8]) can be called as f(&rgb). That coercion is the everyday bridge.
You initialise with [value; N] when every element starts the same, or with a literal list. A large array of a non-Copy type is awkward because [x; N] requires T: Copy. For those, std::array::from_fn(|i| ...) builds each element by index. try_from on a slice produces an array when the length matches.
Arrays are the right type for a fixed protocol field, a hash digest, a small lookup table, a matrix row whose width is part of the problem. They are the wrong type for a list the user can grow. Putting a huge array on the stack — [u8; 1_000_000] as a local — can overflow the stack. Put large buffers in a Vec or Box<[T; N]>.
Pattern matching works: let [r, g, b] = rgb; binds each element. let [first, rest @ ..] = bytes; binds a prefix. This is one reason arrays show up in parsers: the length is in the type, so a successful match is a proof of length.
When you reach for an array: N is known and small or is a protocol constant. When you reach for Vec: N varies. When you reach for Box<[T]>: you have a fixed length decided at runtime and you do not need to grow.
Code Examples
fn sum3(xs: [i32; 3]) -> i32 {
xs[0] + xs[1] + xs[2]
}
fn main() {
let rgb = [12, 80, 210];
println!("{}", sum3(rgb)); // prints: 302
let [r, g, _b] = rgb;
println!("{r} {g}"); // prints: 12 80
let same = [0u8; 4];
println!("{:?}", same); // prints: [0, 0, 0, 0]
}Common Gotchas
Length is part of the type
You cannot pass `[u8; 16]` to a `[u8; 4]` parameter. Take a slice when length varies.
Large stack arrays overflow the stack
A megabyte local array is a crash waiting for a small thread stack. Use `Vec` or box it.
`[x; N]` needs `Copy`
For `String` or other non-`Copy` types, use `std::array::from_fn`.
Arrays coerce to slices
Write APIs as `&[T]`. Keep `[T; N]` at the boundary where the length is a guarantee.