Skip to main content

Rust

Day 9: Arrays

Hello again, Rustaceans! 🦀

Today, we’re going to explore arrays in Rust. Arrays are a fundamental data structure that allow us to store multiple values of the same type in a single variable. They’re incredibly useful for organizing data and making our code more efficient and readable.

Let’s start by creating an array. In Rust, arrays are declared using the syntax let variable_name : [data_type; size] . This means you specify the type of data the array will hold, and the size of the array.

There are several ways to initialize arrays in Rust. One common method is to initialize them with specific values. Here’s an example:

let my_numbers: [u32; 5] = [1, 2, 3, 4, 5];

In this example, my_numbers is an array that holds five unsigned 32-bit integers. We’ve specified the values of the array elements directly in the declaration.

But what if you want to initialize all elements of an array to the same value? Rust has got you covered:

let my_numbers = [0; 5];

In this case, my_array is an array of five integers, all initialized to 0. This is a handy shortcut when you need an array with a default value.

Remember, the size of arrays in Rust is fixed at compile time, and each element in the array must be of the same type. This can be different from other datatypes like vector that can be resized dynamically.

💡
Note that you don't need to specify the array data type and size if you are initializing it right away. Rust can infert it.

Let's print our array. We can use a for loop to iterate over the array and print each element. Here’s how you might do it:

fn main() {
    let my_numbers = [1, 2, 3, 4, 5];
    for number in my_numbers {
        print!("{} ", number);
    }
}

However, if you have numerous arrays in your codebase, repeating this process for each one can become cumbersome. There is a much better way to do this. If you recall our discussion on the Debug and Display traits a few days back (here’s the link if you need a refresher), we can leverage these traits to print our arrays. Instead of the Display placeholder, we can use the Debug placeholder, or we can implement the Display trait for the array. Here’s how you can do it: