Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

each_mut()

Returns an array of mutable references on elements.

each_ref()

Returns an array of references on elements.

map(f)

Applies function f() on each element of the array and returns an array of the same size.

Here is an array of four i32 integers:

[1, 2, 3, 4]

If we want to specify another integer type, we need also to specify the array size:

[-8, 4, 6]

We may construct an array using the repetition of a value:

[4, 4, 4]

Accessing a value is done using the indexing operator []:

3

Any type whose size is known at compile time may be used to build an array. Here is a table of booleans:

[true, false, false]

A table of floats:

[1.5, -45.23, 10.3]

A table of strings:

["a", "ab", "abc"]

And a table of tuples:

[(1, 4), (-10, 18)]

Note that all tuples must be similar (i.e.: same element types, same number of elements), otherwise compilation will fail:

[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
───╯