#Reverse slice iteration

1 messages · Page 1 of 1 (latest)

maiden cairn
#

This doesn't work:

var arr: [5]u64 = undefined;
// ... set up array ... //
for (arr[arr.len-1 .. 0]) |x| { }

Gets the error

start index 4 is larger than end index 0
  1. This is kind of a bummer to me because it'd be nice if reverse ranges were a thing - though I can see where maybe people might think they'd be bugprone or something, and you'd have to decide whether to make the end index inclusive/exclusive, etc.
  2. Is there a convenient way to do this kind of backwards iteration other than:
var i: u64 = arr.len;
while (i >= 0) : (i -= 1) {
   arr[i] ...
}

?

I'm guessing there isn't but figured I'd ask.

#

I could build a reverse iterator class of some kind and do

var reversed = ReverseIterator(u64) { .slice = arr[0..] };
while (reversed.next()) |x| { ... }
austere anchor
modern horizon
maiden cairn
#

@modern horizon perfect! exactly what I was hoping I was missing 🙂