Search code examples
loopsiteratorintegerrangezig

Zig for loop range iterator with custom int type


I am using a for loop to iterate over an integer range such as:

for (0..256) |i| {

My issue is that I need i to be of type u21, but it is currently usize. I can just hit it with the manual @intCast inside the loop, but I was wondering if there is a better way.

I was hoping the following would work, but it still gives me a usize:

for (@as(u21, 0)..256) |i| {

Any suggestions to elegantly accomplish this?


Solution

  • The documentation doesn't mention any tricks. But you can use a while loop:

    var i: u21 = 0;
    while (i < 256) : (i += 1) {
        // ...
    }