w3resource

Rust Array Manipulation & Slicing

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

Write a Rust program that creates an array of strings with size 6 and initializes it with days of the week. Remove the last 2 elements from the array and slice it to get a sub-array containing the first 3 days. Print the resulting sub-array.

Sample Solution:

Rust Code:

fn main() {
    // Declare an array of strings with size 6 and initialize it with days of the week
    let days_of_week: [&str; 6] = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    // Slice the array to get a sub-array containing the first 3 days
    let sub_array = &days_of_week[0..3];

    // Print the resulting sub-array
    println!("First 3 days of the week: {:?}", sub_array);
}

Output:

First 3 days of the week: ["Monday", "Tuesday", "Wednesday"]

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 days_of_week: [&str; 6] = [...];: This line declares an array named days_of_week of type [&str; 6] (array of string slices with size 6) and initializes it with days of the week as string slices.
  • let sub_array = &days_of_week[0..3];: This line slices the 'days_of_week' array to get a sub-array containing the first 3 days (from index 0 to index 2).
  • println!("First 3 days of the week: {:?}", sub_array);: This line prints the resulting sub-array to the console using debug formatting. The {:?} format specifier prints the array slice elements.

Rust Code Editor:

Previous: Rust Array Initialization & Slicing.
Next: Rust Array Sorting & Slicing.

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