Arrays

An array is a fixed-size collection of elements of the same type. We declare them with square brackets:

let array = [1, 2, 3, 4]; let array: [i16; 4] = [1, 2, 3, 4];

The second line shows how to specify the type of an array. An alternative way to do that is to use a literal suffix:

let array = [1u8, 2, 3, 4];

A literal suffix is the composition of a literal (that is, a constant) and a type suffix, so with theÂ 1 Â constant and theÂ u8 Â type, we get 1u8 . Literal suffixes can only be used on numbers. This declares an array of 4 elements of theÂ u8 Â type. Array indexing starts at 0 and bounds checking is done at runtime. Bounds checking is used to prevent accessing memory that is out of bounds, for instance, trying to access the element after the end of an array. While this can slow down the software a bit, it can be optimized in many cases. The following code will trigger a panic because theÂ 4 Â index is one past the end of the array:

println!("{}", array[4]);

At runtime, we see the following message:

thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/main.rs:5:20 note: Run with `RUST_BACKTRACE=1` for a backtrace.

Another way to declare an array is:

let array = [0u8; 100];

This declares an array of 100 elements, where all of them areÂ 0 .

Slices Arrays are fixed-size, but if we want to create a function that works with arrays of any size, we need to use another type: a slice. A slice is a view into a contiguous sequence: it can be a view of the whole array, or a part of it. Slices are fat pointers, in addition to the pointer to the data, they contain a size. Here's a function that returns a reference to the first element of a slice: fn first<T>(slice: &[T]) -> &T { &slice[0] } Here, we use a generic type without bound since we don't use any operation on values of theÂ T Â type. TheÂ &[T] Â parameter type is a slice of T . The return type is &T , which is a reference on values of theÂ T Â type. The body of the function is &slice[0] , which returns a reference to the first element of the slice. Here's how to call this function with an array: println!("{}", first(&array)); We can create slice for only a portion of an array, as shown in the following example: println!("{}", first(&array[2..])); &array[2..] creates a slice that starts at theÂ 2 Â index until the end of the array (hence no index after .. ). Both indices are optional, so we could also write &array[..10] for the first 10 elements of the array, &array[5..10] for the elements with the 5 to 9 index (inclusive), or &array[..] for all the elements.