How to Make a Reverse Ordered For Loop in Rust
Created
Modified
Using rev Function
The .rev()
function reverses an iterator’s direction. Usually, iterators iterate from left to right. After using rev(), an iterator will instead iterate from right to left. For example,
fn main() {
for x in (0..5).rev() {
println!("{}", x);
}
}
4 3 2 1 0
This also works for most Iterators:
fn main() {
let v = vec!["a", "b", "c"];
for x in v.iter().rev() {
println!("{}", x);
}
}
c b a