Rust Lang

Rust Arrays

An array refers to a collection of objects of the same type. Arrays are incredibly useful in a plethora of cases. Therefore, as programmers, it is essential to be familiar with arrays and how to use them in our programs.

This article will explore how we can create and use arrays in the Rust programming language.

Rust Arrays

In Rust, like most programming languages, we represent an array by a pair of square brackets. Rust requires the size of an array to be known before compilation. If the size of an array is undefined at compile-time, this is known as a slice.

Create Rust Array

There are two major ways to create arrays in Rust:

By adding the elements of the array to a pair of square brackets. This is the simplest and most common method of array creation. We can express the syntax for this method of array creation as shown:

let array_name: [f64, 3] = [3.141, 100.2443, 223.554]

The above creates an array under the variable name “array_name”. In our case, the array holds 64-bit signed floating-point values as specified by the f64 value. The size of the array is 3. This means that it can hold up to 3 elements.

We refer to the second method of creating an array as a repeat expression. The syntax is as [N, X] where the array contains the value of X is copied N times.

Rust Declare Array

There are various types of arrays in Rust. Each type is determined by the method of declaration used. The following are the arrays and how to declare them.

Arrays without Size and Type

The first type of array is one without the size and type. This is a very useful method for quick array operations.

To declare an array without type or size, use the syntax as shown below:

let array_name = [elements];

Here, we use the let keyword, followed by the name of the variable. Next, we use the assignment operator, followed by the elements of the array inside a pair of square brackets.

An example is as shown:

let arr = [1,2,3];

The compiler determines the type of the array based on the elements stored in it. The total number of elements in the array becomes its size.

Arrays with Type and Size

The second type of array is one with both a type and size during declaration. For this type of array, we set the data type of the elements we wish to store in the array and how many elements the array will hold.

The syntax for this array creation is as shown below:

let array_name: [data_type; array_size] = [array_elements];

An example is as shown below:

fn main() {

let arr:[i32; 3] = [1,2,3];

}

The above creates an array called “arr” that holds 3, 32-bit signed integers.

Arrays with Default Values

The third type of array in Rust is one that contains a default value. In this type of array, all the elements in the array hold a single identical value which you can update as you see fit.

The syntax is as shown:

let array_name:[data_type; array_size] = [default_value; array_size];

An example of such an array is as shown:

fn main() {

let arr:[&str; 3] = ["nil";3];

}

The above example creates an array of &str and size 3. We also include a default value, “nil”. Hence, all three elements in the array will hold the default value unless updated.

Rust Print Array

We can print an array using the println! macro and the debug trait in the std::fmt. An example is as shown:

fn main() {

let arr:[&str; 3] = ["nil";3];

println!("{:?}", arr);

}

The above code should print the array as shown:

Rust Array Indexing

Although we can print the entire array using the debug trait from the fmt module, we can access individual elements from the array using its index.

In Rust, array indexing starts at 0. This means that the first element in the array is at index 0, and the second is at index 1 and so on.

To access an element by its index, we use the name of the array followed by the index of the element we wish to access inside a pair of square brackets.

An example is as shown:

fn main() {

let arr:[&str; 3] = ["nil";3];

println!("{}", arr[0]);

}

The example above should be the element at index 0 or the first element in the array.

To get the last element in the array, we use the length of the array – 1 since indexing starts at 0.

An example is as shown:

fn main() {

let databases:[&str; 3] = ["MySQL", "MongoDB", "SQL Server"];

println!("{}", databases[databases.len() - 1]);

}

In the example above, we use the len() function to get the length of the array. This built-in function returns the length (number of elements) in the array.

The program above should return the element at index 2 as:

Rust Iterate Over Array

Another common operation when working with arrays is iterating over each element in the array. In Rust, we can accomplish this using a for loop.

An example is as shown below:

fn main() {

let databases:[&str; 3] = ["MySQL", "MongoDB", "SQL Server"];

for i in 0..databases.len() {

println!("Index: {}, Element: {}", i, databases[i]);

}

}

The example program above uses a simple for loop to iterate over the elements in the array. To get the number of elements in the array, we can use the len() function. Inside the for loop, we access each element based on the index.

The resulting values are as shown:

Rust Array Mutability

Like all variables in Rust, arrays are immutable by default. Hence, trying to change the array will cause an error.

An example is as shown:

fn main() {

let databases:[&str; 3] = ["MySQL", "MongoDB", "SQL Server"];

databases[0] = "PostgreSQL";

}

The program above attempts to change the value of the element at index 0. Running the code above will return an error as shown:

We can set the array to mutable using the mut keyword to avoid this error. The code is as shown below:

let mut databases:[&str; 3] = ["MySQL", "MongoDB", "SQL Server"];

This makes the array mutable, allowing you to change its values as you see fit.

Conclusion

This article explored how to create and use arrays in Rust. Keep in mind that arrays can be expanded to do so much more. Consider the Rust docs for more information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list