w3resource

Rust Vector Mapping guide

Rust Vectors: Exercise-7 with Solution

Write a Rust program to create a vector with integers 1 to 5. Map each element of the vector to its cube and print the resulting vector.

Sample Solution:

Rust Code:

// Define the main function
fn main() {
    // Create a vector with integers 1 to 5
    let numbers: Vec<i32> = (1..=5).collect(); // Use the collect() method to create a vector from a range

    // Map each element of the vector to its cube and collect the results into a new vector
    let cubes: Vec<i32> = numbers.iter() // Convert the vector into an iterator
        .map(|&x| x.pow(3)) // Use the map method to apply a function to each element, cubing it
        .collect(); // Collect the mapped elements back into a vector

    // Print the resulting vector with cubes
    println!("Cubes: {:?}", cubes);
}

Output:

Cubes: [1, 8, 27, 64, 125]

Explanation:

Here is a brief explanation of the above Rust code:

  • Define the main function: fn main() { starts the definition of the main function, which is the entry point of the Rust program.
  • Create a vector with integers 1 to 5: The let numbers: Vec<i32> = (1..=5).collect(); line creates a vector 'numbers' containing integers from 1 to 5. The range (1..=5) specifies the sequence of numbers from 1 to 5 inclusive, and the collect() method gathers these into a vector.
  • Map each element to its cube: The program then maps each element of 'numbers' to its cube. This is done by converting 'numbers' into an iterator with numbers.iter(), applying a function to each element that calculates its cube using .map(|&x| x.pow(3)), and collecting the results back into a new vector 'cubes'.
  • Print the resulting vector: Finally, the program prints the 'cubes' vector using println!("Cubes: {:?}", cubes);. The {:?} syntax within the "println!" macro indicates that the vector should be printed using its debug representation, which in this case, is a list of the cubed values.

Rust Code Editor:

Previous: Rust vector filtering guide.
Next: Rust File Operations: Copy, Move, Delete with Error handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.