Looping over an integer range in Zig

Viewed 107

Is a while-loop like this the idiomatic way to loop over an integer range in Zig?

var i: i32 = 5;
while (i<10): (i+=1) {
    std.debug.print("{}\n", .{i});
}

I first tried the python-like

for (5..10) |i| {
    // ....

but that doesn't work.

1 Answers

zig has no concept of integer range loops but there's a hack by nektro which create a random []void slice, so you can iterate with for loop

const std = @import("std");

fn range(len: usize) []const void {
    return @as([*]void, undefined)[0..len];
}

for (range(10)) |_, i| {
    std.debug.print("{d}\n", .{i});
}
Related