for loops in Zig
for walks elements; add 0.. and it hands you the index too.
const std = @import("std");
pub fn main() void {
const temps = [_]i32{ 61, 68, 74, 79 };
// for walks the elements; adding 0.. pairs each with its index.
for (temps) |t| {
std.debug.print("{d} ", .{t});
}
std.debug.print("\n", .{});
for (temps, 0..) |t, day| {
std.debug.print("day {d}: {d} F\n", .{ day + 1, t });
}
}
How it works
for (temps) |t|captures each element between the pipes.for (temps, 0..) |t, day|iterates the array and a counter in lockstep.- There is no C-style for — ranges and slices are the only things to walk.
Keywords and builtins used here
constfnfori32pubvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 321
- Tokens
- 112
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 90 seconds.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.