Create An Array Of Number In Rust
Code snippet for how to Create An Array Of Number In Rust with sample and detail explanation
Rust is a modern, powerful programming language that ensures high performance, secure software with easy maintainability. This tutorial will guide you through one of the basics in Rust – Creating an array of numbers.
Code snippet to Create an Array Of Number In Rust
fn main() {
let array_num: [i32; 5] = [10, 20, 30, 40, 50];
for i in &array_num {
println!("{}", i);
}
}
Code Explanation for Creating an Array Of Number In Rust
In Rust, arrays are the ordered list of elements of the same type. The size of an array is fixed at compile time. Array data structure lets programmers specify the number of elements the array can hold.
Here’s a breakdown of our Rust code:
-
fn main() {}
- This is the main function where our program starts running. -
let array_num: [i32; 5] = [10, 20, 30, 40, 50];
- Here, we are declaring an array namedarray_num
. Thelet
keyword is used to declare variable binding in Rust. The: [i32; 5]
denotes that this array contains five elements of typei32
(integer of 32 bits). We then initialize our array with five numbers: 10, 20, 30, 40, 50. The numbers are written in array brackets[]
and separated by commas. -
for i in &array_num { println!("{}", i); }
- This is a basic for loop that is iterating over thearray_num
. The&
beforearray_num
is used to create a reference to the array, so that we don’t lose ownership of our array. In each iteration, it will print the value of the array elementi
.
Once this line executes, your program will print out each number element in the console one after another: 10, 20, 30, 40, 50.
Remember, Rust arrays hold a specific count of the same type of values which means all values should be of the same type. This is one of the many safety measures Rust offers that helps developers prevent common mistakes.
And that’s it! You have now created an array of numbers in Rust! This might seem like a small achievement, and in a way, it is - but grasping these fundamentals is key to understanding and mastering Rust.