w3resource

Rust Vector Slicing Guide

Rust Vectors: Exercise-10 with Solution

Write a Rust program to create a vector with integers 1 to 10. Slice the vector to get a sub-vector containing elements from index 3 to index 7 (inclusive). Print the sub-vector.

Sample Solution:

Rust Code:

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

    // Slice the vector to get a sub-vector containing elements from index 3 to index 7 (inclusive)
    let sub_vector = &numbers[3..=7]; // Use slicing syntax to create a sub-vector

    // Print the sub-vector
    println!("Sub-vector: {:?}", sub_vector);
}

Output:

Sub-vector: [4, 5, 6, 7, 8]

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 10: The line let numbers: Vec<i32> = (1..=10).collect(); creates a vector "numbers" containing integers from 1 to 10 using the "collect()" method with a range (1..=10).
  • Slice the vector to get a sub-vector: The line let sub_vector = &numbers[3..=7]; slices the "numbers" vector to get a sub-vector containing elements from index 3 to index 7 (inclusive). The slicing syntax [start..=end] is used to specify the range of indices.
  • Print the sub-vector: The line println!("Sub-vector: {:?}", sub_vector); prints the sub-vector to the console using the "println!" macro. The {:?} syntax within the "println!" macro indicates that the sub-vector should be printed using its debug representation.

Rust Code Editor:

Previous: Rust Vector Searching Guide.

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.