To iterate over a vector in Rust, you can use a for
loop to access each element of the vector one by one.
In this example,
vec
with a series of integer values using the vec!
macro.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.println!
macro to print the current value of the loop variable item
.println!
macro sends the value of item
to the console, allowing us to see each element of the vector as it is processed.fn main() {
let vec = vec![10, 20, 30, 40, 50];
for item in &vec {
println!("{}", item);
}
}
10 20 30 40 50
In this example,
vec
with a series of string values using the vec!
macro.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.println!
macro to print the current value of the loop variable item
.println!
macro sends the value of item
to the console, allowing us to see each element of the vector as it is processed.fn main() {
let vec = vec!["apple", "banana", "cherry", "date", "elderberry"];
for item in &vec {
println!("{}", item);
}
}
apple banana cherry date elderberry
In this tutorial, we learned How to Iterate Over a Vector in Rust language with well detailed examples.