You can use a screwdriver to hammer nails. That doesn’t mean the screwdriver was intended for hammering nails.
Everything about the for
loop and its restrictions sure suggest that it’s explicitly designed for iterating over array elements in order. Your ranges can’t have negative bounds, you can’t change the step size or iterate in reverse and your captured variables are usize
integers. If Zig range expressions were intended for general counting, they would probably resemble a Lua-style for i=start,end,step
loop more closely than they do today.
However, it’s possible you might get something similar to what you ask for if/when allow integer types to be any range · Issue #3806 · ziglang/zig · GitHub (which the compiler team has expressed great interest in) is implemented. This is all conjecture, but presumably, once implemented, a range expression like n..m
could be captured as a variable of type
@Int(
@min(math.minInt(@TypeOf(n)), math.minInt(@TypeOf(n))),
@max(math.maxInt(@TypeOf(n)), math.maxInt(@TypeOf(m))) + 1,
)
which when the bounds are comptime-known like in 0..10
will be @Int(0, 10)
, which coerces to wider integers including u8
(which will be an alias for @Int(0, 256)
). Negative bounds might still be off-limit.