Rust, Software Development

Rust – How to Declare and Initialize an Array

Rust is a strange language for some. However, it is a fun programming language to play (or work) with. When we need arrays in Rust, we declare and initialize an array simultaneously with size and default values.

Declare And Initialize Array Literals in Rust

Arrays store values of the same type. Therefore, we can create arrays of type i32, String, &str, and even struct. Consider the following sample codes that declare and initialize an array literal of i32  type with a size of 4.

When we run the codes, we get the following output.

Let’s create another array sample. The following codes declare and initialize an array literal of &str type with 2  elements.

When we run these codes, we get the following result.

How about an array of struct instances? We can also declare and initialize an array of the Struct type. Consider the following codes. We have a struct Student that holds i32  and String values.

Then, we declare and initialize an array type Student. Note that we need to create instances of Student to supply the array with value for its initialization. When we run the codes, we get the following output.

Array with Default values

Sometimes it is cumbersome to initialize an array with values, especially when it’s relatively long. For example, we would need to provide integer values for an array with 100 elements explicitly. Fortunately, there’s a shortcut to that. We could declare and initialize an array with the same initial values and modify them later in the application. Consider the following sample codes below; we declare and initialize an array of size 5  with a default "[change me]".

With this shortcut, we only need to specify one default value for all elements of the array. When we run the codes, we get the following output.

We can use the same technique when declaring and initializing multi-dimensional arrays.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like