liveBook · Manning

Iterator

As explained in Systems Programming with Zig

The iterator pattern provides an abstraction for accessing elements sequentially without exposing their underlying representation.

A recipe book stores ingredients for many recipes in one array list. Callers could scan the list and filter by recipe ID, but every caller would then depend on that storage layout. An iterator puts the scan behind a sequential interface, so callers can ask for the next ingredient without handling the representation themselves. section 5.3.3

In Zig, an iterator is a convention rather than a language feature. It keeps the state needed to produce successive values; a mutable next method advances that state and returns an optional value. A null result signals exhaustion. section 5.3.3 section 4.1.3

Listing 5.9 Make it an iterator
const IngredientIterator = struct {
    book: *const RecipeBook, #1
    recipe_id: RecipeId,
    index: usize = 0, #2

    fn next(iter: *@This()) ?Ingredient {
        return while (iter.index < iter.book.ingredients.items.len) { #3
            const ingredient = iter.book.ingredients.items[iter.index];
            iter.index += 1;
            if (ingredient.recipe_id == iter.recipe_id) { #3
                return ingredient;
            }
        } else null;
    }
};

fn iterateIngredients(
    self: *const RecipeBook,
    recipe_id: RecipeId,
) IngredientIterator {
    return .{ .book = self, .recipe_id = recipe_id };
}

The ingredient iterator holds a book pointer, a recipe ID, and an index. Each next call advances through the shared array until it finds a match or runs out of ingredients. section 5.3.3

The caller creates a mutable iterator and loops while next returns an ingredient. Filtering stays in one place, so a storage change need not force every caller to rewrite its loop. The trade-off is judgment: abstracting too early can waste effort, while waiting too long lets brittle access patterns spread. section 5.3.3

Listing 4.1 Counting the dictionary words
fn countWordlist(text: []const u8) usize {
    var count: usize = 0;
    var word_iter = std.mem.tokenizeScalar(u8, text, '\n'); #1
    while (word_iter.next()) |_| { #2
        count += 1;
    }

    return count;
}

A standard-library iterator can do the same job for generated values: tokenizeScalar splits a word list on newlines, and next supplies tokens to a counting loop. section 4.1.3

The pattern also works across a C interface, though without Zig's optional-return and method syntax. An explicit start function initializes the iterator; a next function writes a result through a pointer and returns a boolean indicating whether it produced one. section 5.4.2

Listing 5.20 Discovering all the recipes
pub const RecipeIterator = extern struct { #1
    book: *const RecipeBook,
    recipe_num: c_int,
};

export fn recipe_iter_start( #2
    book: *const RecipeBook,
    out_iter: *RecipeIterator,
) void {
    out_iter.* = .{ .book = book, .recipe_num = 0 };
}

export fn recipe_iter_next( #3
    iter: *RecipeIterator,
    result: *RecipeId,
) bool {
    while (iter.recipe_num < iter.book.recipes.count()) { #4
        const next_id: RecipeId = @fromBackingInt(@intCast(iter.recipe_num));
        iter.recipe_num += 1;

        if (iter.book.recipes.contains(next_id)) {
            result.* = next_id; #5
            return true; #5
        }
    }

    return false; #6
}

The exported recipe iterator stores its position in an extern struct and exposes separate start and next functions. section 5.4.2

How Systems Programming with Zig covers it

How deep it goes
Works through iterator state, filtering, exhaustion, and a C-compatible interface, alongside abstraction trade-offs.
Examples
Uses recipe ingredient filtering, newline-delimited word counting, and recipe enumeration through a C interface.
What you can do after
Builds an iterator from scratch and applies the pattern through a C-compatible interface.
How it connects
Connects iterators with array lists, filtering, optionals, tokenization, and foreign-function interfaces.

Also explained in

Compare how 17 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.