To iterate over a vector in reverse order in Rust, you can use the .iter().rev()
method, which provides an iterator yielding references to the elements of the vector in reverse order.
In this example,
num_vec
containing several numeric values.iter().rev()
method to obtain a reverse iterator over the elements of num_vec
.for
loop, which allows us to access each element of the vector in reverse order.fn main() {
let num_vec = vec![10, 20, 30, 40, 50];
for num in num_vec.iter().rev() {
println!("{}", num);
}
}
50 40 30 20 10
In this example,
str_vec
containing several string values.iter().rev()
method to obtain a reverse iterator over the elements of str_vec
.for
loop, allowing us to access each string element of the vector in reverse order.fn main() {
let str_vec = vec!["apple", "banana", "cherry", "date"];
for s in str_vec.iter().rev() {
println!("{}", s);
}
}
date cherry banana apple
In this tutorial, we learned How to Iterate Over a Vector in Reverse Order in Rust language with well detailed examples.