OneBite.Dev - Coding blog in a bite size

Find The Sum Of All Elements In An Array In Rust

Code snippet for how to Find The Sum Of All Elements In An Array In Rust with sample and detail explanation

Rust is a powerful programming language that allows us to manage complex tasks with ease. One such task we might need to perform is computing the sum of all elements in an array. Below, we will see how this is done in Rust, examining both the code and its explanation.

Code snippet: Find The Sum Of All Elements In An Array In Rust

Below is a simple Rust program that finds the sum of all elements in an array:

fn main() {
    let array = [1, 2, 3, 4, 5];
    let sum: i32 = array.iter().sum();

    println!("Sum of all elements in the array is: {}", sum);
}

This program will compute the sum of all numbers in the array and output it to the console.

Code Explanation: Find The Sum Of All Elements In An Array In Rust

Let’s dissect the code snippet above to understand how it works:

At the heart of the program is an array of integers, which is this line of code:

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

This declare an array of integers named array. This array contains five integers one through five.

Following that, we determine the sum of the array’s elements using this piece of code:

let sum: i32 = array.iter().sum();

Here, we declare a variable sum as an integer type (i32). The iter() function is called to create an iterator over the items in the array. We then call the sum() function on the iterator, which will iterate over each item in the array and add them together. The resultant value is then stored in the sum variable.

Finally, we print the sum of all elements in the array to the console:

println!("Sum of all elements in the array is: {}", sum);

Here, println! is a macro that prints to the console. The {} placeholder inside the string is replaced by the value of the sum variable.

That’s all there is to it! You can adjust the array as you see fit and the program will calculate the sum of its elements. Rust’s iterator and sum functions make this task straightforward and efficient.

rust