Rust Vector manipulation & slicing
Rust Vectors, Arrays, and Slices: Exercise-2 with Solution
Write a Rust program that creates a vector of characters containing the letters 'A' to 'Z'. Remove the first 7 elements from the vector and then slice it to get the last 10 elements. Print the resulting sub-vector.
Sample Solution:
Rust Code:
fn main() {
// Create a vector of characters containing the letters 'A' to 'Z'
let mut letters: Vec = ('A'..='Z').collect();
// Remove the first 7 elements from the vector
letters.drain(0..7);
// Slice the vector to get the last 10 elements
let sub_vector = &letters[letters.len() - 10..];
// Print the resulting sub-vector
println!("Resulting Sub-Vector: {:?}", sub_vector);
}
Output:
Resulting Sub-Vector: ['Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
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 letters: Vec<char> = ('A'..='Z').collect();: This line creates a vector named 'letters' of type Vec<char> and initializes it with characters from 'A' to 'Z' using the "collect()" method on a range.
- letters.drain(0..7);: This line removes the first 7 elements from the 'letters' vector using the "drain()" method with a range from 0 to 7 (exclusive).
- let sub_vector = &letters[letters.len() - 10..];: This line slices the 'letters' vector to get the last 10 elements. It uses the length of the vector to determine the starting index for the slice and then takes the last 10 elements.
- println!("Resulting Sub-Vector: {:?}", sub_vector);: This line prints the resulting 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 Vector creation & slicing.
Next: Rust Array access guide.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics