Zig Iterators
You’ve already used iterators several times without the name: splitting text with tokenizeScalar, looping over a hash map, popping items off an ArrayList. They all look the same: while (it.next()) |x| { ... }. Zig has no special iterator feature in the language. An iterator is just a struct with a next method, and that one simple convention is used all over the standard library. Once you see how it works, you can write your own in a few lines.
The pattern
Section titled “The pattern”Here’s the shape you’ll see everywhere:
const std = @import("std");
pub fn main() void { const csv = "red,green,,blue";
var it = std.mem.splitScalar(u8, csv, ','); while (it.next()) |part| { std.debug.print("[{s}]\n", .{part}); }}Output:
[red][green][][blue]Three pieces work together:
std.mem.splitScalar(...)makes an iterator. Nothing has been split yet; it just remembers the text and where it’s up to.it.next()does one step: it finds the next piece and returns it, or returnsnullwhen there’s nothing left. So its return type is an optional, here?[]const u8.while (it.next()) |part|keeps callingnextand runs the body with each value, stopping at the firstnull. That’s the while with optionals loop from the language reference.
This is lazy: each piece is found only when you ask for it. If you break after the first match, the rest of the text is never even looked at. And no memory is allocated; the pieces are slices of the original text.
Why the iterator must be a var
Section titled “Why the iterator must be a var”Each call to next moves the iterator forward, so next has to change it. That’s why its first parameter is self: *Self, a pointer that allows changes, and why the iterator itself must be a var. Make it const and Zig stops you:
const std = @import("std");
pub fn main() void { const it = std.mem.splitScalar(u8, "a,b,c", ','); while (it.next()) |part| { std.debug.print("{s}\n", .{part}); }}main.zig:5:14: error: expected type '*T', found '*const T' while (it.next()) |part| { ~~^~~~~main.zig:5:14: note: T = mem.SplitIterator(u8,.scalar)main.zig:5:14: note: cast discards const qualifier“cast discards const qualifier” is Zig’s way of saying “this method wants to change the value, but you said it’s constant”. You’ll see this error a lot while you’re learning. The fix is always the same: var it = ....
Why not for?
Section titled “Why not for?”A for loop works on things whose length is known: arrays, slices, ranges like 0..10, tuples. An iterator doesn’t know how many items are coming until it runs out, so for refuses it:
const std = @import("std");
pub fn main() void { var it = std.mem.splitScalar(u8, "a,b,c", ','); for (it) |part| { std.debug.print("{s}\n", .{part}); }}main.zig:5:10: error: type 'mem.SplitIterator(u8,.scalar)' is not indexable and not a range for (it) |part| { ^~main.zig:5:10: note: for loop operand must be a range, array, slice, tuple, or vectorSo the rule of thumb is simple: slices and arrays get for, iterators get while. If you come from Python or JavaScript, where for works on anything iterable, this is the main habit to change.
Writing your own iterator
Section titled “Writing your own iterator”Any struct with a next method that returns an optional can be used this way. Here’s one that counts down:
const std = @import("std");
const Countdown = struct { current: u32,
fn next(self: *Countdown) ?u32 { if (self.current == 0) return null; const value = self.current; self.current -= 1; return value; }};
pub fn main() void { var countdown: Countdown = .{ .current = 3 }; while (countdown.next()) |n| { std.debug.print("{d}...\n", .{n}); } std.debug.print("liftoff!\n", .{});}Output:
3...2...1...liftoff!That’s the whole recipe:
- Fields hold the state: where you are, and anything you need to find the next value.
next(self: *Self) ?Treturns the next value and moves the state forward, or returnsnullwhen you’re done.
No interface to implement, no trait to declare. The while loop doesn’t care what type countdown is; it only calls .next() and checks for null. Once next has returned null, a well-behaved iterator keeps returning null if you call it again, and Countdown does.
An iterator over a slice
Section titled “An iterator over a slice”Most useful iterators walk over some data you already have. This one hands out a slice in chunks of a fixed size, which is handy for things like printing data in rows. It works for any item type, using the “function that returns a type” trick from Zig Generic Data Structures:
const std = @import("std");
fn Chunks(comptime T: type) type { return struct { items: []const T, size: usize, pos: usize = 0,
const Self = @This();
fn next(self: *Self) ?[]const T { if (self.pos >= self.items.len) return null; const end = @min(self.pos + self.size, self.items.len); const chunk = self.items[self.pos..end]; self.pos = end; return chunk; } };}
pub fn main() void { const days = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var weeks: Chunks(u8) = .{ .items = &days, .size = 7 }; while (weeks.next()) |week| { std.debug.print("{any}\n", .{week}); }
var letters: Chunks(u8) = .{ .items = "abcdefgh", .size = 3 }; while (letters.next()) |group| { std.debug.print("[{s}]", .{group}); } std.debug.print("\n", .{});}Output:
{ 1, 2, 3, 4, 5, 6, 7 }{ 8, 9, 10 }[abc][def][gh]The last chunk is shorter when the items don’t divide evenly, thanks to @min. pos has a default value of 0, so you only fill in items and size when you make one. And like splitScalar, it never copies or allocates: every chunk is a slice of the original data.
Iterators that hand out pointers
Section titled “Iterators that hand out pointers”next returns copies of the values. To change items as you go, an iterator can return pointers instead, ?*T. The hash map’s valueIterator() does this, and here’s a small one of our own that walks a task list:
const std = @import("std");
const Task = struct { name: []const u8, done: bool = false,};
const TodoIterator = struct { tasks: []Task, index: usize = 0,
fn next(self: *TodoIterator) ?*Task { while (self.index < self.tasks.len) { const task = &self.tasks[self.index]; self.index += 1; if (!task.done) return task; } return null; }};
pub fn main() void { var tasks = [_]Task{ .{ .name = "write tests" }, .{ .name = "fix bug", .done = true }, .{ .name = "update docs" }, };
var todo: TodoIterator = .{ .tasks = &tasks }; while (todo.next()) |task| { std.debug.print("doing: {s}\n", .{task.name}); task.done = true; }
for (tasks) |t| std.debug.print("{s}: {}\n", .{ t.name, t.done });}Output:
doing: write testsdoing: update docswrite tests: truefix bug: trueupdate docs: trueThis iterator also filters: it skips tasks that are already done, so the loop only sees the ones left to do. Because it hands out *Task, setting task.done = true changes the real array. The iterator holds a []Task (not []const Task) so that it’s allowed to give out changeable pointers.
Iterators that can fail
Section titled “Iterators that can fail”Sometimes getting the next item can go wrong: reading a file, parsing a number. Then next returns an error union around the optional, !?T, and you add try in the loop: while (try it.next()) |x|. Here’s an iterator that reads comma-separated numbers:
const std = @import("std");
const NumberIterator = struct { parts: std.mem.SplitIterator(u8, .scalar),
fn init(text: []const u8) NumberIterator { return .{ .parts = std.mem.splitScalar(u8, text, ',') }; }
fn next(self: *NumberIterator) !?i32 { const part = self.parts.next() orelse return null; return try std.fmt.parseInt(i32, part, 10); }};
fn sum(text: []const u8) !i32 { var total: i32 = 0; var numbers = NumberIterator.init(text); while (try numbers.next()) |n| total += n; return total;}
pub fn main() void { for ([_][]const u8{ "4,8,15,16", "4,x,15" }) |text| { if (sum(text)) |total| { std.debug.print("{s} adds up to {d}\n", .{ text, total }); } else |err| { std.debug.print("{s} failed: {t}\n", .{ text, err }); } }}Output:
4,8,15,16 adds up to 434,x,15 failed: InvalidCharacterRead !?i32 from the outside in: “maybe an error; if not, maybe a number; if not, we’re done”. try peels off the error (and passes it up, see Zig Try & Catch), and the while peels off the optional. Notice that NumberIterator is built on top of another iterator: it keeps a SplitIterator as a field and calls its next. Wrapping one iterator in another is a common way to build bigger ones.
Iterators in the standard library
Section titled “Iterators in the standard library”Now that you know the pattern, you’ll spot it everywhere. A few worth knowing:
const std = @import("std");
pub fn main() void { var request = std.mem.splitScalar(u8, "GET /index.html HTTP/1.1", ' '); const method = request.next().?; std.debug.print("method: {s}, next: {?s}, rest: {s}\n", .{ method, request.peek(), request.rest() });
var pairs = std.mem.window(u8, "abcdef", 2, 1); while (pairs.next()) |pair| std.debug.print("[{s}]", .{pair}); std.debug.print("\n", .{});
var backwards = std.mem.reverseIterator(@as([]const u8, "stressed")); while (backwards.next()) |c| std.debug.print("{c}", .{c}); std.debug.print("\n", .{});}Output:
method: GET, next: /index.html, rest: /index.html HTTP/1.1[ab][bc][cd][de][ef]dessertsstd.mem.splitScalar,splitSequence,tokenizeScalar,tokenizeAnysplit text. Split iterators also havepeek()(look at the next piece without moving),rest()(everything not yet returned) andreset()(start over).std.mem.window(T, slice, size, advance)gives overlapping (or spaced) windows of a slice.std.mem.reverseIterator(slice)walks a slice backwards.- Hash maps have
iterator(),keyIterator()andvalueIterator(); bit sets haveiterator(.{})(see Zig Other Collections). std.unicode.Utf8Viewhas an iterator whosenextCodepoint()walks a string one Unicode character at a time instead of one byte at a time.
Not every iterator’s method is called next (that last one is nextCodepoint), but they all work the same way: call it in a while, stop at null.
Practice
Section titled “Practice”1. Even numbers up to a limit
Section titled “1. Even numbers up to a limit”Write an iterator Evens with fields current: u32 = 0 and limit: u32, whose next returns 0, 2, 4, ... up to and including limit, then null. Print everything it gives for limit = 10.
Hint: in next, return null if current > limit; otherwise save current, add 2, and return the saved value.
Show solution
const std = @import("std");
const Evens = struct { current: u32 = 0, limit: u32,
fn next(self: *Evens) ?u32 { if (self.current > self.limit) return null; const value = self.current; self.current += 2; return value; }};
pub fn main() void { var evens: Evens = .{ .limit = 10 }; while (evens.next()) |n| std.debug.print("{d}\n", .{n});}Output:
0246810current has a default value, so you only give limit when making the iterator.
2. Count the words
Section titled “2. Count the words”Use std.mem.tokenizeScalar to count the words in " the quick brown fox " (note the extra spaces), and print the count and the longest word.
Hint: tokenizeScalar skips empty pieces, unlike splitScalar. Keep a longest: []const u8 = "" and replace it when you find a longer word.
Show solution
const std = @import("std");
pub fn main() void { const text = " the quick brown fox ";
var count: usize = 0; var longest: []const u8 = ""; var words = std.mem.tokenizeScalar(u8, text, ' '); while (words.next()) |word| { count += 1; if (word.len > longest.len) longest = word; } std.debug.print("{d} words, longest: {s}\n", .{ count, longest });}Output:
4 words, longest: quickWith splitScalar you’d also get empty pieces between the doubled spaces, so the count would be wrong. quick and brown are both five letters; > keeps the first one.
3. Fibonacci numbers
Section titled “3. Fibonacci numbers”Write an iterator that gives Fibonacci numbers (1, 1, 2, 3, 5, 8, ...) and stops at the first number above 100.
Hint: keep two fields, a: u32 = 1 and b: u32 = 1. Each next returns a, then moves both forward: the new a is b, the new b is a + b.
Show solution
const std = @import("std");
const Fibonacci = struct { a: u32 = 1, b: u32 = 1, max: u32,
fn next(self: *Fibonacci) ?u32 { if (self.a > self.max) return null; const value = self.a; const sum = self.a + self.b; self.a = self.b; self.b = sum; return value; }};
pub fn main() void { var fib: Fibonacci = .{ .max = 100 }; while (fib.next()) |n| std.debug.print("{d},", .{n}); std.debug.print("\n", .{});}Output:
1,1,2,3,5,8,13,21,34,55,89,The sum is saved in sum before a changes. Updating both fields in one line with self.a, self.b = .{ self.b, self.a + self.b }; looks neater, but it compiles and gives the wrong numbers (1 1 2 4 8 16...): the first field is assigned before the second value is worked out, so self.a + self.b already sees the new a.
- An iterator is a struct with a
nextmethod that returns?T: a value, ornullwhen it’s finished. - Use it with
while (it.next()) |x|.foronly works on arrays, slices, ranges and tuples. - The iterator must be a
var, becausenexttakesself: *Selfand moves it forward. - Iterators are lazy and usually don’t allocate; text splitters return slices of the original.
- Return
?*Tto let the loop change items, and!?Twhen getting the next item can fail (while (try it.next()) |x|). - The standard library is full of them:
splitScalar,tokenizeScalar,window,reverseIterator, map iterators.
Next up: Zig Other Collections, linked lists, priority queues, bit sets and when you’d use each.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: while with Optionals: the loop form every iterator relies on.
- Zig language reference: while with Error Unions: looping when the condition can fail.
- std.mem source (0.17.1):
SplitIterator,TokenIterator,WindowIteratorandReverseIterator, all short and easy to read. - zig.guide: Iterators: a short community page on the same pattern. Check which Zig version it targets before copying code.