OneBite.Dev - Coding blog in a bite size

Declare An Array In Rust

Code snippet for how to Declare An Array In Rust with sample and detail explanation

Rust programming language is loved by developers due to its performance and safety, especially in concurrent contexts. This article will take you through how to declare an array in Rust, from the basic syntax to understanding in-depth functionality in an easy, step-by-step manner.

Code snippet for Declaring an Array in Rust

Here is a simple code snippet that demonstrates how to declare an array in Rust.

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

Code Explanation for Declaring an Array in Rust

Now, let’s break down the code piece by piece to gain a better understanding of how arrays in Rust work.

  1. fn main(): This starts the definition of the main function, which is the entry point of any Rust program.

  2. let arr: [i32; 5] = [1, 2, 3, 4, 5]; : Here we declare and initialise the array. let is a keyword used for variable declaration (also known as ‘binding’) in Rust. arr is the name we’ve chosen for our variable. [i32; 5] specifies the type and size of our array - in this case, an array of integers (i32) of length 5. [1, 2, 3, 4, 5]; is the array of values that arr will hold.

  3. println!("{:?}", arr); : The println! macro is used here to print the array arr onto the console. ”{:?}” is a placeholder for the array we want to output, in this case, arr.

Running this code outputs [1, 2, 3, 4, 5] to the console, indicating that our array was created and populated successfully.

Remember that in Rust, arrays are of fixed size. If you attempt to modify an array to be larger or smaller than its initial size, you will encounter an error. If you require a list-like structure with a mutable size, consider using other data structures such as Vectors.

There you have it, that’s how you declare an array in Rust! By understanding this, you now have one more tool in your Rust programming arsenal. Happy coding!

rust