Arrays and Slices

An array is a fixed-size sequence of values of the same type. They are written with, where   is the type the array contains and   is the number of elements in the array. A slice is similar, but its size is only known at runtime, so they are written as just. Arrays and slices cannot grow or shrink; their size is fixed from creation.

Example
The variable  has the type. Because its length is part of its type, the compiler ensures that it can't be assigned an array with the wrong length.

Slices are dynamically sized. This means that they can only exist behind a reference or in pointer type such as. There are two ways to create a slice:


 * Index an array or slice with a range, e.g.  creates a slice of the whole array, whereas   only creates a slice of the 2nd to 7th element of the array.
 * Put an array behind a reference or in a pointer type and then coerce it into a slice. The coercion is possible if the reference or pointer type implements the trait.

Because slices are dynamically sized, references to slices are fat — they're twice as big as normal references, because they have to store the slice's memory address as well as their length:

Arrays and const generics
Arrays in Rust have a constant in their type definition. As of Rust 1.51.0, a subset of const generics has been stabilized, so you may create a type that's generic over some integer constants, and use that constant for array size.