Rust Vector Mapping & Slicing
Write a Rust program that creates a vector of floating-point numbers. Map each element of the vector to its square root. Slice the resulting vector to get a sub-vector containing the elements from index 2 to index 6. Print the sub-vector.
Sample Solution:
Rust Code:
fn main() {
// Create a vector of floating-point numbers
let numbers: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
// Map each element of the vector to its square root
let squared_numbers: Vec<f64> = numbers.into_iter().map(|x| x.sqrt()).collect();
// Slice the resulting vector to get a sub-vector containing the elements from index 2 to index 6
let sub_vector = &squared_numbers[2..7];
// Print the sub-vector
println!("Sub-Vector: {:?}", sub_vector);
}
Output:
Sub-Vector: [1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907]
Explanation:
Here is a brief explanation of the above Rust code:
- fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
- let numbers: Vec<f64> = vec![1.0, 2.0, ...];: This line creates a vector named numbers of type Vec<f64> (vector of floating-point numbers) and initializes it with some floating-point numbers.
- let squared_numbers: Vec<f64> = ...: This line maps each element of the numbers vector to its square root using the "map()" method and collects the results into a new vector named 'squared_numbers'.
- let sub_vector = &squared_numbers[2..7];: This line slices the 'squared_numbers' vector to get a sub-vector containing the elements from index 2 to index 6.
- println!("Sub-Vector: {:?}", sub_vector);: This line prints the sub-vector to the console using debug formatting. The {:?} format specifier prints the elements of the vector.
Rust Code Editor:
Previous: Rust Vector Filtering & Slicing.
Next: Rust Array Initialization & Slicing.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics