w3resource

Rust Program: Calculate differences in Arrays

Rust Iterators and Iterator Adapters: Exercise-14 with Solution

Write a Rust program that iterates over a vector of arrays [i32; 2] and calculates the difference between the first and second elements of each array.

Sample Solution:

Rust Code:

fn main() {
    // Define a vector of arrays
    let arrays = vec![[10, 20], [30, 20], [150, 60]];

    // Iterate over each array, calculate the difference between the first and second elements,
    // and collect the differences into a new vector
    let differences: Vec<i32> = arrays
        .iter() // Use iter() to borrow the vector
        .map(|arr| arr[0] - arr[1]) // Calculate the difference between the first and second elements
        .collect(); // Collect the differences into a new vector

    println!("Original arrays: {:?}", arrays);
    println!("Differences: {:?}", differences);
}

Output:

Original arrays: [[10, 20], [30, 20], [150, 60]]
Differences: [-10, 10, 90]

Explanation:

In the exercise above,

  • Start by defining a vector 'arrays' containing arrays of type [i32; 2].
  • Then, we use the "iter()" method to iterate over each array in the 'arrays' vector.
  • Within the "map()" function, we calculate the difference between the first and second elements of each array using array indexing (arr[0] and arr[1]).
  • The "map()" function returns an iterator over the calculated differences.
  • Finally, we collect these differences into a new vector of type 'Vec' using the "collect()" method.Print both the original vector of arrays and the vector containing the calculated differences using "println!()" statements.

Rust Code Editor:


Previous: Rust Program: Extract Some values.
Next: Rust Program: Find Prime numbers in Range.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-14.php