How do Arrays work in Rust programming?

Rust

Like all other languages Rust also have Array supports. An array is a collection of many elements of the same Data type. You can specify the length of the array at the time of code writing. This will fix the size of the array.

A simple example of an Array in Rust looks like:

fn main() 
{
let a = [a, b, c, d, e];
}

so the syntax is simple, just using square brackets with the array values inside separated by a comma.

Arrays are of fixed size and stored on the stack. Array does not allow you features like growing or shrinking at runtime. So when you choose to use array you need to be sure about your size requirements.

Runtime size control is supported by collections like vector which we will discuss later.

As I said when you are sure of size requirements then we prefer array, like in this example below, where we are sure that a week will always have 7 days only.

fn main() 
{
let DaysofWeek= ["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday", "Sunday"];
}

Another syntax to declare an array is:

fn main() 
{
let arr: [i32; 5] = [1, 2, 3, 4, 5];
}

Here we are explicitly specifying the data type of the elements and count of elements this array is going to hold.

Same Items Array:

If you have need of an array which needs to store the same element values n number of times then you can declare it using shorthand syntax like :

fn main() 
{
let a = [2; 5] // [Value; n];
}

This will give you a array of size 5 and all values are 2 like this

a = [2, 2, 2, 2, 2]

Accessing Array Elements

The array is stored in stack and it can be easily accessed by indexing like most of the languages do. The indexing starts with 0 and goes till n-1 for an array of size n. So you can access the first element with index 0 and the last element by index n-1.

fn main() 
{
let a = [1, 2, 3, 4, 5];
let a1= a[0];
let a2= a[1];
}

Invalid Array Access/ Overflow

If you will try to access an element beyond the size of the array then your code will be able to detect this at runtime. It can not be caught at compile time. So as a developer you will need to make sure you are not crossing the boundary.


fn main() 
{
let a = [1, 2, 3, 4, 5];
let element = a[6];

println!(" 6th index element is: {}", element);
}

If you will try this , then your program will crash.