w3resource

Rust Vector creation & slicing

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

Write a Rust program that creates a vector of integers from 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:

fn main() {
    // Create a vector of integers from 1 to 10
    let mut numbers: Vec = (1..=10).collect();

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

    // 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:

  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let mut numbers: Vec<i32> = (1..=10).collect();: This line creates a vector named numbers of type Vec<i32> and initializes it with integers from 1 to 10 using the collect() method on a range.
  • let sub_vector = &numbers[3..=7];: This line slices the 'numbers' vector to get a sub-vector containing elements from index 3 to index 7 (inclusive). The '&' symbol is used to borrow a reference to the sub-vector.
  • println!("Sub-Vector: {:?}", sub_vector);: This line prints the sub-vector to the console using debug formatting. The {:?} format specifier is used to print the elements of the vector.

Rust Code Editor:

Previous: Rust Vectors, Arrays, and Slices Exercises.
Next: Rust Vector manipulation & 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-1.php