w3resource

Rust Array Mapping & Slicing

Rust Vectors, Arrays, and Slices: Exercise-10 with Solution

Write a Rust program that creates an array of integers of size 9. Map each element of the array to its cube. Slice the resulting array to get a sub-array containing the elements from index 1 to index 6. Print the sub-array.

Sample Solution:

Rust Code:

fn main() {
    // Declare an array of integers with size 9
    let numbers: [i32; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    // Map each element of the array to its cube
    let cubed_numbers: Vec<i32> = numbers.iter().map(|&x| x * x * x).collect();

    // Slice the resulting vector to get a sub-array containing the elements from index 1 to index 6
    let sub_array = &cubed_numbers[1..7];

    // Print the sub-array
    println!("Sub-Array: {:?}", sub_array);
}

Output:

Sub-Array: [8, 27, 64, 125, 216, 343]

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: [i32; 9] = [...];: This line declares an array named 'numbers' of type [i32; 9] (array of integers with size 9) and initializes it with integers from 1 to 9.
  • let cubed_numbers: Vec<i32> = ...: This line maps each element of the 'numbers' array to its cube using the map method and collects the results into a new vector named cubed_numbers.

  • let sub_array = &cubed_numbers[1..7];: This line slices the 'cubed_numbers' vector to get a sub-array containing the elements from index 1 to index 6.
  • println!("Sub-Array: {:?}", sub_array);: This line prints the sub-array to the console using debug formatting. The {:?} format specifier is used to print the elements of the array slice.

Rust Code Editor:

Previous: Rust Array Filtering & Slicing.
Next: Rust Hashmaps Exercises with Solutions

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/collections_and_data_structures/rust-vectors-arrays-slices-exercise-10.php