w3resource

Rust Program: Swap Tuple elements

Rust Iterators and Iterator Adapters: Exercise-12 with Solution

Write a Rust program that iterates over a vector of tuples (i32, i32) and swaps the elements of each tuple.

Sample Solution:

Rust Code:

fn main() {
    let tuples = vec![(10, 20), (30, 40), (50, 60)];

    // Iterate over each tuple, swap the elements, and collect into a new vector
    let swapped_tuples: Vec<(i32, i32)> = tuples
        .iter() // Use iter() instead of into_iter() to borrow the vector
        .map(|&(x, y)| (y, x)) // Swap the elements of each tuple
        .collect();

    println!("Original tuples: {:?}", tuples);
    println!("Swapped tuples: {:?}", swapped_tuples);
}

Output:

Original tuples: [(10, 20), (30, 40), (50, 60)]
Swapped tuples: [(20, 10), (40, 30), (60, 50)]

Explanation:

In the exercise above,

  • let tuples = vec![(10, 20), (30, 40), (50, 60)];: Creates a vector 'tuples' containing tuples of integers.
  • let swapped_tuples: Vec<(i32, i32)> = tuples.iter().map(|&(x, y)| (y, x)).collect();: Iterates over each tuple in 'tuples', swaps the elements of each tuple, and collects the results into a new vector 'swapped_tuples'. The "iter()" method is used to borrow the vector without consuming it. The "map()" method applies a closure to each tuple, swapping its elements. Finally, the "collect()" method collects the modified tuples into a new vector.
  • println!("Original tuples: {:?}", tuples);: Prints the original vector of tuples.
  • println!("Swapped tuples: {:?}", swapped_tuples);: Prints the vector of tuples with swapped elements.

Rust Code Editor:


Previous: Rust Program: Cube Vector elements.
Next: Rust Program: Extract Some values.

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://w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-12.php