For loops can be used to iterate over sequences. |
|
const std = @import("std"); const print = std.debug.print; |
|
pub fn main() !void { var array = [_]u32{ 1, 2, 3 }; |
|
Here, we iterate over |
for (array) |elem| { print("by val: {}\n", .{elem}); } |
To iterate by reference, we can loop over a slice of |
for (&array) |*elem| { elem.* += 100; print("by ref: {}\n", .{elem.*}); } |
Here, we iterate over multiple sequences. Note that both sequences must have the same length. |
for (array, &array) |val, *ref| { _ = val; _ = ref; } |
You may also specify a range with the |
for (0.., array) |i, elem| { print("{}: {}\n", .{ i, elem }); } |
To ignore the elements of a sequence, use |
for (array) |_| {} } |
$ zig run for.zig by val: 1 by val: 2 by val: 3 by ref: 101 by ref: 102 by ref: 103 0: 101 1: 102 2: 103 |