Rust Array

www.‮itfigi‬dea.com

In Rust, an array is a fixed-size collection of items of the same type. Once an array is created, its size cannot be changed. To create an array, you can use the following syntax:

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

In this example, we're creating an array of integers with 5 elements. You can access individual elements of the array using the index operator []. Here's an example:

let my_array = [1, 2, 3, 4, 5];
let second_element = my_array[1]; // gets the second element (index 1) of the array

println!("Second element: {}", second_element);

In this example, we're accessing the second element (index 1) of the array and storing it in the second_element variable. We're then printing the value of second_element using the println! macro.

You can also use a loop to iterate over the elements of an array. Here's an example:

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

for num in my_array.iter() {
    println!("Number: {}", num);
}

In this example, we're using a for loop to iterate over each element of the array using the iter method. Inside the loop, we're printing the current value of num using the println! macro.

It's important to note that Rust arrays have a fixed size and can't be resized, so if you need to add or remove elements from a collection, you might want to use a vector instead.