Rust Program: Cube Vector elements
Rust Iterators and Iterator Adapters: Exercise-11 with Solution
Write a Rust program that iterates over a vector of integers and cubes for each element.
Sample Solution:
Rust Code:
fn main() {
// Define a vector of integers
let numbers = vec![1, 2, 3, 4, 5, 6, 7];
// Cube each element and collect the results into a new vector
let cubes: Vec<i32> = numbers.iter().map(|&x| x * x * x).collect();
// Print the original vector
println!("Original numbers: {:?}", numbers);
// Print the vector of cubed numbers
println!("Cubed numbers: {:?}", cubes);
}
Output:
Original numbers: [1, 2, 3, 4, 5, 6, 7] Cubed numbers: [1, 8, 27, 64, 125, 216, 343]
Explanation:
In the exercise above,
- let numbers = vec![1, 2, 3, 4, 5, 6, 7];: Initializes a vector 'numbers' containing integers from 1 to 7.
- let cubes: Vec<i32> = numbers.iter().map(|&x| x x x).collect();: Applies the cube function to each element of the 'numbers' vector using the 'map' iterator adapter. It collects the results into a new vector called 'cubes'.
- println!("Original numbers: {:?}", numbers);: Prints the original vector of numbers.
- println!("Cubed numbers: {:?}", cubes);: Prints the vector of cubed numbers.
Rust Code Editor:
Previous: Rust Program: Convert strings to Uppercase.
Next: Rust Program: Swap Tuple elements.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics