Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Zig Practice Exercises

Twelve Zig exercises on allocators, errors, comptime, generics, C interop and testing, with hints, worked solutions, review questions and ideas for bigger projects.

Reading about allocators and comptime only takes you so far; you learn Zig by writing it and by reading compiler errors. This page collects twelve exercises for the topics of this chapter group. They are graded from easy to hard, and each has a hint. Solutions for the trickiest ones follow after the list. Try each exercise before reading the solution, and write a test block for every one of them.

Work in a scratch project made with zig init, and run zig build test after every exercise. Use std.testing.allocator so leaks fail your tests (see Testing in Zig).

The exercises

1. Reverse in place (easy). Write fn reverse(comptime T: type, items: []T) void that reverses a slice without allocating. Hint: swap items[i] with items[len - 1 - i] for the first half, or use two indexes that move toward each other.

2. Join strings (easy). Write fn join(gpa: Allocator, parts: []const []const u8, sep: []const u8) ![]u8 returning a newly allocated string. Hint: compute the total length first, alloc once, then copy with @memcpy. Remember the caller owns the result.

3. Safe division (easy). Write fn divide(a: i32, b: i32) !i32 that returns error.DivisionByZero for zero and error.Overflow for minInt(i32) / -1. Test both with expectError.

4. Parse key=value lines (medium). Given text with lines like name=Zig, fill a StringHashMap([]const u8) using std.mem.splitScalar and std.mem.trim. Decide who owns the key and value slices and document it. Bad lines return error.MalformedLine.

5. Cleanup order (medium). Write a function that allocates three buffers and fails on the third step with an error. Add errdefers so the testing allocator reports no leak. Then deliberately remove one errdefer and watch the test fail.

6. Generic min/max (medium). Write fn minMax(comptime T: type, items: []const T) ?struct { min: T, max: T }. Return null for an empty slice and make it a compile error (@compileError) for types that are not integers or floats.

7. Generic ring buffer (medium). Implement RingBuffer(comptime T: type, comptime capacity: usize) with push, pop and len, with no allocator. push on a full buffer returns error.Full. Test wrap-around.

8. Comptime table (medium). Build a [26]u8 table at compile time mapping each lowercase letter to its ROT13 letter, then write fn rot13(text: []u8) void that uses it. Hint: a blk: labeled comptime block with a for loop.

9. Field printer (hard). Write fn printFields(value: anytype) void that uses @typeInfo and inline for to print every field of a struct as name = value. Print strings with and everything else with . Hint: check @TypeOf(field value) against []const u8.

10. Linked list with iterator (hard). Implement a generic singly linked list with prepend, popFront, deinit, and an iterator() method returning a struct with next() ?T. Test with std.testing.allocator.

11. C interop (hard). @cImport <string.h> and call strlen on a [:0]const u8; then call qsort to sort a [8]c_int array with a callconv(.c) comparison function. Compare with the same program in C.

12. A tiny tokenizer (hard). Write a tokenizer for arithmetic expressions that returns a tagged union Token = union(enum) { number: f64, plus, minus, star, slash, lparen, rparen }. Make an iterator with next() !?Token that returns error.UnexpectedCharacter for garbage. Then connect it to the stack VM of Project: a stack-based calculator VM by converting infix to postfix (the shunting-yard algorithm).

Worked solutions

Exercise 1: reverse

ZIG
fn reverse(comptime T: type, items: []T) void {
    var i: usize = 0;
    var j: usize = items.len;
    while (i + 1 < j) : (i += 1) {
        j -= 1;
        std.mem.swap(T, &items[i], &items[j]);
    }
}

test "reverse" {
    var a = [_]u8{ 1, 2, 3, 4, 5 };
    reverse(u8, &a);
    try std.testing.expectEqualSlices(u8, &.{ 5, 4, 3, 2, 1 }, &a);
}

The standard library already has std.mem.reverse; writing your own once teaches slice indexing and the unsigned usize trap (note that we avoid j - 1 going below zero by stopping at i + 1 < j).

Exercise 2: join

ZIG
fn join(gpa: std.mem.Allocator, parts: []const []const u8, sep: []const u8) ![]u8 {
    if (parts.len == 0) return gpa.alloc(u8, 0);

    var total: usize = sep.len * (parts.len - 1);
    for (parts) |p| total += p.len;

    const out = try gpa.alloc(u8, total);
    var pos: usize = 0;
    for (parts, 0..) |p, i| {
        if (i > 0) {
            @memcpy(out[pos..][0..sep.len], sep);
            pos += sep.len;
        }
        @memcpy(out[pos..][0..p.len], p);
        pos += p.len;
    }
    return out;
}

test "join" {
    const gpa = std.testing.allocator;
    const s = try join(gpa, &.{ "a", "b", "c" }, ", ");
    defer gpa.free(s);
    try std.testing.expectEqualStrings("a, b, c", s);
}

There is no failure path after the single allocation, so no errdefer is needed. out[pos..][0..n] slices from pos and then takes exactly n items, a common idiom.

Exercise 3: safe division

ZIG
fn divide(a: i32, b: i32) error{ DivisionByZero, Overflow }!i32 {
    if (b == 0) return error.DivisionByZero;
    if (a == std.math.minInt(i32) and b == -1) return error.Overflow;
    return @divTrunc(a, b);
}

Zig makes you pick a division builtin for signed integers: @divTrunc, @divFloor or @divExact, because they differ for negative numbers (-7 / 2 is -3 with truncation and -4 with floor).

Exercise 8: ROT13 table

ZIG
const rot13_table = blk: {
    var t: [26]u8 = undefined;
    for (&t, 0..) |*slot, i| {
        slot.* = @intCast('a' + (i + 13) % 26);
    }
    break :blk t;
};

fn rot13(text: []u8) void {
    for (text) |*c| {
        if (c.* >= 'a' and c.* <= 'z') c.* = rot13_table[c.* - 'a'];
    }
}

The compiler evaluates the labeled block once; the table lives in the binary. Applying rot13 twice returns the original text, which makes a nice test.

Runnable practice in Go

The logic in several of these exercises can be rehearsed in Go while you learn Zig syntax. This block implements exercises 1, 3 and 8 so you can compare behaviour: in-place reverse, division with named errors, and a ROT13 table built once.

Go Exercises 1, 3 and 8 as a Go stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Review questions

Without looking back, answer these in your own words, then check the chapters.

  1. Why does a function that allocates take an allocator parameter, and who frees the memory it returns?
  2. What is the difference between defer and errdefer, and where must you write each?
  3. When would you return ?T and when !T?
  4. What does comptime T: type do, and what does the compiler produce for two different Ts?
  5. Why is inline for needed to loop over struct fields?
  6. How do you pass a Zig function to a C library that wants a callback?
  7. What does zig build test do, and why use std.testing.allocator?
  8. Which optimize mode would you choose for development, for a server, and for a tiny embedded program?

Ideas for bigger projects

  • A Markdown to HTML converter for a subset of the syntax, with an arena per document.
  • A JSON pretty-printer that uses a tagged union for values and a recursive-descent parser.
  • A bump-allocated Lisp interpreter with an environment StringHashMap.
  • A CLI tool with subcommands, cross-compiled for three platforms with one zig build.
  • A game of life with a comptime-sized grid and a fixed buffer allocator, as the memory-bounded exercise of choice.
  • A wrapper for a C library such as zlib: @cImport the header and expose a safe, allocator-aware Zig API with error sets instead of integer return codes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 2, why compute the total length before allocating?

    One exact allocation is simple, fast and leaves no growth failure paths to clean up.
  2. 2. Why does Zig force you to pick @divTrunc, @divFloor or @divExact for signed integers?

    The rounding direction for negative results is ambiguous, so the language asks you to state it.
  3. 3. How do you make a table available at no runtime cost?

    A comptime-evaluated table is stored in the binary's data section.
  4. 4. What should you do before reading an exercise solution?

    Struggling with compiler errors is how Zig sticks.

Summary

  • Twelve exercises cover slices, allocation, errors, comptime tables, generics, C interop and tokenizing.
  • Test everything with std.testing.allocator; deliberately break cleanup code to see the leak report.
  • Review questions check the chapter concepts; the project ideas stretch them.
  • You now have the main building blocks of Zig: explicit memory, errors as values, comptime, C interop and the build system.

Next: Zig tutorial overview