Start learning free

LESSON 92 OF 348 · ARRAYS I

Static Arrays in Rust in Rust

Lesson

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In Rust, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by writing the element type and length inside [T; N], followed by the array's name, like this:

let array_of_strings: [&str; 5] = [""; 5];

In this program we created an array named array_of_strings that consists of 5 &str items.

These 5 items are initialized with empty strings "" automatically.


Creation & Initialization:

There is a way to initialize an array at creation by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

let array_of_strings = ["AlgoCademy", "coding", "static arrays"];

We created an array named array_of_strings which consits of 3 string items: "AlgoCademy", "coding" and "static arrays".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Static Arrays in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free