In Rust, an array is defined with a type and a fixed size. Arrays are stored on the stack memory (see Stack), and thus must be used with reasonable sizes. It provides few methods (see Table 1 and array), but can be coerced to slices, which provide most of the interesting methods (see Table 2).
Table 1:Some methods of array
Method | Description |
|---|---|
| Returns an array of mutable references on elements. |
| Returns an array of references on elements. |
| Applies function |
Here is an array of four i32 integers:
let a = [1, 2, 3, 4];
a[1, 2, 3, 4]If we want to specify another integer type, we need also to specify the array size:
let a: [i16; 3] = [-8, 4, 6];
a[-8, 4, 6]We may construct an array using the repetition of a value:
let a = [4/*value*/; 3/*Number of repetition*/];
a[4, 4, 4]Accessing a value is done using the indexing operator []:
let a = [1, 2, 3, 4];
a[2]3Any type whose size is known at compile time may be used to build an array. Here is a table of booleans:
let a = [true, false, false];
a[true, false, false]A table of floats:
let a = [1.5, -45.23, 10.3];
a[1.5, -45.23, 10.3]A table of strings:
let a = ["a", "ab", "abc"];
a["a", "ab", "abc"]And a table of tuples:
let a = [(1, 4), (-10, 18)];
a[(1, 4), (-10, 18)]Note that all tuples must be similar (i.e.: same element types, same number of elements), otherwise compilation will fail:
let a = [(1, 4), (-10, 18, 4)];
a[E0308] Error: mismatched types
╭─[ command_10:1:1 ]
│
1 │ let a = [(1, 4), (-10, 18, 4)];
│ ──────┬─────
│ ╰─────── expected a tuple with 2 elements, found one with 3 elements
───╯