Menu
Coddy logo textTech

Declaring Arrays

Part of the Fundamentals section of Coddy's Rust journey — lesson 55 of 75.

An array is a fixed-size collection where all elements must be of the same type from the start. Arrays are created using square brackets [], and the items inside the array are separated with commas.

Here is an example of how to create an array:

let numbers = [1, 2, 3, 4, 5];

To check the length of the array, we can use the .len() field:

let length = numbers.len();

The variable length will hold 5 because there are 5 elements in the array.

Another way to create an array using the : keyword followed by the array type and size:

let numbers: [i32; 5] = [0; 5];

Creates an array of 5 integers, all initialized to 0

challenge icon

Challenge

Easy

Create an array called shopping_list that contains the following items: bread, eggs, milk, and butter.

Cheat sheet

Arrays are fixed-size collections where all elements must be of the same type. Create arrays using square brackets [] with comma-separated items:

let numbers = [1, 2, 3, 4, 5];

Check array length using .len():

let length = numbers.len();

Create arrays with type annotation and initialization:

let numbers: [i32; 5] = [0; 5]; // Creates array of 5 integers, all initialized to 0

Try it yourself

fn main() {
    // Create the shopping_list array here
    
    
    // Don't change the code below
    println!("Shopping List:");
    for i in 0..shopping_list.len() {
        println!("{}", shopping_list[i]);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals