Rust Vector Initialization Guide
Rust Vectors: Exercise-1 with Solution
Write a Rust program to create an empty vector and add integers 1 to 10 to it. Print the vector.
Sample Solution:
Rust Code:
// Define the main function
fn main() {
// Create an empty vector to store integers
let mut numbers = Vec::new();
// Use a for loop to add integers 1 to 10 to the vector
for i in 1..=10 {
numbers.push(i); // Add the current value of i to the vector
}
// Print the vector
println!("The vector is: {:?}", numbers);
}
Output:
The vector is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:
The above program uses a "for" loop to iterate over integers from 1 to 10 (inclusive) and adds each integer to the vector using the "push" method. Finally, it prints the vector using the "println" macro with the {:?} format specifier to display the contents of the vector.
Rust Code Editor:
Previous: Rust Vectors Exercises.
Next: Rust Vector Operations 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-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics