0

Rust – How to Declare and Initialize an Array

In Rust, we declare and initialize arrays at the same time.

Array Literals

Integers

The sample codes below create an array literal of i32  type with size of 4.

Output

Strings

The following codes create an array literal of &str type with 2  elements.

Output

Structs

We can also create an array of Struct type.

Output

Array with Default values

Sometimes we want an array with initial values to be modified at a later stage in the application. In the sample codes below, we create an array of size 5  with default values of  "[change me]" .

Output

Karl San Gabriel

Karl San Gabriel

Professional Software Developer