Rust Vector access guide
Rust Vectors: Exercise-3 with Solution
Write a Rust program to create a vector with integers 1 to 10. Print the element at index 4.
Sample Solution:
Rust Code:
// 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
// Print the element at index 4
if let Some(element) = numbers.get(4) { // Use the get() method to access the element at index 4
println!("Element at index 4 is: {}", element);
} else {
println!("Index 4 is out of bounds.");
}
}
Output:
Element at index 4 is: 5
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 program.
- let numbers: Vec<i32> = (1..=10).collect();: This line creates a vector "numbers" containing integers from 1 to 10 using the "collect()" method with a range (1..=10).
- if let Some(element) = numbers.get(4) {: This line attempts to access the element at index 4 using the "get()" method. If the element exists (i.e., the index is within bounds), it assigns the element to the variable 'element'.
- println!("Element at index 4 is: {}", element);: If the index is within bounds, it prints the element at index 4.
- } else { println!("Index 4 is out of bounds."); }: If the index is out of bounds (i.e., the element does not exist), it prints a message indicating that index 4 is out of bounds.
This program creates a vector with integers from 1 to 10 and then prints the element at index 4. If index 4 is out of bounds, it prints a corresponding error message.
Rust Code Editor:
Previous: Rust Vector Operations Guide.
Next: Rust Vector iteration 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://w3resource.com/rust/collections_and_data_structures/rust-vectors-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics