Reverse for loops

Given that a for loop range [0..123] will iterate up from 0 to 122, will a range [122..-1] iterate down from 122 to 0?

Thanks folks

1 Like

If you want to reverse the order of the items iterated in a for loop, use .rev()

for i in 0..4 {
    print!("{}, ");
}
// Prints:
0, 1, 2, 3, 
// While:
for i in (0..4).rev() {
    print!("{}, ");
}
// Prints:
3, 2, 1, 0, 

This also works for most Iterators:

let x = vec!['a', 'b', 'c'];

for i in x.iter().rev() {
    print!("{}, ");
}
// Prints:
c, b, a, 
6 Likes

Cool. Thanks! @OptimisticPeach

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.