Skip to content

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.

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:

  1. std.mem.splitScalar(...) makes an iterator. Nothing has been split yet; it just remembers the text and where it’s up to.
  2. it.next() does one step: it finds the next piece and returns it, or returns null when there’s nothing left. So its return type is an optional, here ?[]const u8.
  3. while (it.next()) |part| keeps calling next and runs the body with each value, stopping at the first null. 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.

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 = ....

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 vector

So 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.

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) ?T returns the next value and moves the state forward, or returns null when 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.

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.

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 tests
doing: update docs
write tests: true
fix bug: true
update docs: true

This 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.

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 43
4,x,15 failed: InvalidCharacter

Read !?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.

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]
desserts
  • std.mem.splitScalar, splitSequence, tokenizeScalar, tokenizeAny split text. Split iterators also have peek() (look at the next piece without moving), rest() (everything not yet returned) and reset() (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() and valueIterator(); bit sets have iterator(.{}) (see Zig Other Collections).
  • std.unicode.Utf8View has an iterator whose nextCodepoint() 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.

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:

0
2
4
6
8
10

current has a default value, so you only give limit when making the iterator.

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: quick

With 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.

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 next method that returns ?T: a value, or null when it’s finished.
  • Use it with while (it.next()) |x|. for only works on arrays, slices, ranges and tuples.
  • The iterator must be a var, because next takes self: *Self and moves it forward.
  • Iterators are lazy and usually don’t allocate; text splitters return slices of the original.
  • Return ?*T to let the loop change items, and !?T when 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

1. What should an iterator's next return when there are no more items?
2. You wrote const it = std.mem.splitScalar(u8, s, ','); and it.next() fails with "cast discards const qualifier". Why?
3. How do you loop over a custom iterator it?
4. An iterator's next returns !?u32. Which loop fits?