Skip to content

Zig Generic Data Structures

You need a stack of numbers for a calculator, and a stack of strings for an undo history. Same push and pop, different item type. In Java or Rust you’d write Stack<T>. Zig doesn’t have angle brackets: a generic type is a function that returns a type. You call Stack(i32) at compile time, and you get back a brand new struct type built for i32. It sounds odd at first, but it’s the same comptime idea from Zig Generic Functions, and it’s exactly how std.ArrayList(T) and the other standard collections work.

Start with the smallest possible generic type, a box that holds one value:

const std = @import("std");
fn Box(comptime T: type) type {
return struct {
value: T,
};
}
pub fn main() void {
const a: Box(i32) = .{ .value = 42 };
const b: Box([]const u8) = .{ .value = "hello" };
std.debug.print("{d} {s}\n", .{ a.value, b.value });
}

Output:

42 hello

Box takes a type and returns a type. Inside, return struct { value: T }; builds a struct whose field has whatever type T is. So Box(i32) is a struct with an i32 field, and Box([]const u8) is a struct with a string field. Both calls run while compiling, because types only exist then.

The name Box starts with a capital letter on purpose. Zig’s style is: functions that return a type are named like types (TitleCase), and normal functions are camelCase. When you see ArrayList(u8) or HashMap(...), the capital letter tells you a type comes back.

A real stack needs methods, and the methods need to name the struct they belong to. But the struct has no name of its own: it’s created inside Stack. @This() solves that. It means “the struct I’m inside right now”, and it’s usually saved as Self:

const std = @import("std");
fn Stack(comptime T: type) type {
return struct {
items: [8]T = undefined,
len: usize = 0,
const Self = @This();
pub fn push(self: *Self, value: T) error{Full}!void {
if (self.len == self.items.len) return error.Full;
self.items[self.len] = value;
self.len += 1;
}
pub fn pop(self: *Self) ?T {
if (self.len == 0) return null;
self.len -= 1;
return self.items[self.len];
}
};
}
pub fn main() !void {
var numbers: Stack(i32) = .{};
try numbers.push(1);
try numbers.push(2);
try numbers.push(3);
var words: Stack([]const u8) = .{};
try words.push("hello");
try words.push("zig");
while (numbers.pop()) |n| std.debug.print("{d} ", .{n});
std.debug.print("\n", .{});
while (words.pop()) |w| std.debug.print("{s} ", .{w});
std.debug.print("\n", .{});
}

Output:

3 2 1
zig hello

Here’s what each part does:

  • items: [8]T = undefined is room for 8 items, and len counts how many are in use. Both have defaults, so .{} creates an empty stack.
  • push takes self: *Self, a pointer, because it changes the stack. It returns error.Full when there’s no room (see Zig Errors).
  • pop returns ?T: an item, or null when the stack is empty (see Zig Optionals). That’s what makes while (numbers.pop()) |n| stop at the end.

You’ve seen @This() in Zig Struct Methods, where it was a nice-to-have. In generic types it’s the only way to name your own type. You could also write Stack(T) inside the methods and get the same type, but Self is shorter and what everyone uses.

What if two parts of your program both write Stack(i32)? You get the same type both times. Zig remembers each call to a type function with the same arguments:

const std = @import("std");
fn Stack(comptime T: type) type {
return struct {
items: [8]T = undefined,
len: usize = 0,
};
}
pub fn main() void {
std.debug.print("{s}\n", .{@typeName(Stack(i32))});
std.debug.print("{s}\n", .{@typeName(Stack([]const u8))});
std.debug.print("{}\n", .{Stack(i32) == Stack(i32)});
std.debug.print("{}\n", .{Stack(i32) == Stack(u32)});
}

Output:

main.Stack(i32)
main.Stack([]const u8)
true
false

That’s what lets you pass a Stack(i32) made in one function to another function that asks for a Stack(i32). @typeName also shows the arguments, which makes error messages about generic types readable.

Type functions can take any compile-time values, not just types. Let’s make the capacity a parameter, so a short undo history and a big number stack can both use the same code:

const std = @import("std");
fn Stack(comptime T: type, comptime capacity: usize) type {
return struct {
items: [capacity]T = undefined,
len: usize = 0,
const Self = @This();
pub fn push(self: *Self, value: T) error{Full}!void {
if (self.len == capacity) return error.Full;
self.items[self.len] = value;
self.len += 1;
}
pub fn slice(self: *const Self) []const T {
return self.items[0..self.len];
}
};
}
pub fn main() void {
var history: Stack([]const u8, 2) = .{};
for ([_][]const u8{ "type a", "type b", "type c" }) |action| {
history.push(action) catch |err| {
std.debug.print("could not save \"{s}\": {t}\n", .{ action, err });
};
}
std.debug.print("saved: {d}\n", .{history.slice().len});
for (history.slice()) |action| std.debug.print(" {s}\n", .{action});
std.debug.print("{d} bytes vs {d} bytes\n", .{ @sizeOf(Stack(u8, 4)), @sizeOf(Stack(u64, 100)) });
}

Output:

could not save "type c": Full
saved: 2
type a
type b
16 bytes vs 808 bytes

capacity is used as an array length, so it has to be comptime. Stack(u8, 4) and Stack(u64, 100) are again two different types, and @sizeOf shows they really are sized differently: 4 bytes of items plus the 8-byte len (padded to 16), versus 800 bytes of items plus len. The slice method takes *const Self because it only reads, and hands back the used part of the array.

Methods are only checked when you use them

Section titled “Methods are only checked when you use them”

A generic type can have methods that only make sense for some T. Here, sum only works for numbers, because it starts with var total: T = 0:

const std = @import("std");
fn Stack(comptime T: type) type {
return struct {
items: [8]T = undefined,
len: usize = 0,
const Self = @This();
pub fn push(self: *Self, value: T) void {
self.items[self.len] = value;
self.len += 1;
}
pub fn sum(self: Self) T {
var total: T = 0;
for (self.items[0..self.len]) |item| total += item;
return total;
}
};
}
pub fn main() void {
var numbers: Stack(u32) = .{};
numbers.push(4);
numbers.push(6);
std.debug.print("sum: {d}\n", .{numbers.sum()});
var words: Stack([]const u8) = .{};
words.push("hi");
std.debug.print("words: {d}\n", .{words.len});
}

Output:

sum: 10
words: 1

Stack([]const u8) has a sum method that would never compile, and that’s fine, because nobody calls it. Zig only checks a function when something uses it. Add _ = words.sum(); and you get the error you’d expect:

main.zig:16:28: error: expected type '[]const u8', found 'comptime_int'
var total: T = 0;
^

This is handy, but it also means a typo in a method you never call can sit there unnoticed. Tests that call every method (see Zig Testing) catch those.

Forgetting the arguments. Stack on its own is the function, not a type:

fn Stack(comptime T: type) type {
return struct { items: [8]T = undefined, len: usize = 0 };
}
pub fn main() void {
var s: Stack = .{};
_ = &s;
}
main.zig:6:12: error: expected type 'type', found 'fn (comptime type) type'
var s: Stack = .{};
^~~~~

The message says it: Zig wanted a type and got a function that makes types. Write Stack(i32).

Calling a changing method on a const. push needs *Self, a pointer it can change through. A const stack only gives a *const pointer:

fn Stack(comptime T: type) type {
return struct {
items: [8]T = undefined,
len: usize = 0,
const Self = @This();
pub fn push(self: *Self, value: T) void {
self.items[self.len] = value;
self.len += 1;
}
};
}
pub fn main() void {
const s: Stack(i32) = .{};
s.push(1);
}
main.zig:15:6: error: expected type '*main.Stack(i32)', found '*const main.Stack(i32)'
s.push(1);
~^~~~~
main.zig:15:6: note: cast discards const qualifier

Make it var s: Stack(i32) = .{};. This one isn’t special to generics, but it shows up all the time with collections.

Nothing limits you to one type. A Pair holds two values of different types, and its swap method returns a Pair with the types the other way round:

const std = @import("std");
fn Pair(comptime A: type, comptime B: type) type {
return struct {
first: A,
second: B,
const Self = @This();
pub fn swap(self: Self) Pair(B, A) {
return .{ .first = self.second, .second = self.first };
}
};
}
pub fn main() void {
const p: Pair([]const u8, u32) = .{ .first = "apples", .second = 12 };
const q = p.swap();
std.debug.print("{s}: {d}\n", .{ p.first, p.second });
std.debug.print("{d}: {s}\n", .{ q.first, q.second });
std.debug.print("{s}\n", .{@typeName(@TypeOf(q))});
}

Output:

apples: 12
12: apples
main.Pair(u32,[]const u8)

swap returns Pair(B, A), a different type built from the same function. Calling a type function inside its own result is normal.

Now you can read the standard library’s collections. std.ArrayList is a function that takes a type and returns a struct, just like our Stack, except its items live in memory from an allocator so it can grow:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var list: std.ArrayList(i32) = .empty;
defer list.deinit(gpa);
try list.append(gpa, 10);
try list.append(gpa, 20);
std.debug.print("{any}\n", .{list.items});
std.debug.print("{s}\n", .{@typeName(std.ArrayList(i32))});
}

Output:

{ 10, 20 }
array_list.Aligned(i32,null)

The type name gives away a detail: std.ArrayList(i32) is a shortcut for a more general Aligned(i32, null) type in the file array_list.zig. You’ll learn ArrayList properly in Zig ArrayList. If you’re curious, open lib/std/array_list.zig from your Zig install and look for return struct: you’ll find const Self = @This(); and methods taking self: *Self, the same shape as the stack above. The language reference on generic data structures shows the pattern too, and @This has its own short section.

Write Grid(comptime T: type, comptime width: usize, comptime height: usize) that holds cells: [height][width]T, with get(self, x, y) T and set(self: *Self, x, y, value: T) void. Make a 3 by 2 grid of u8 filled with '.', set (1, 0) to '#' and print the rows.

Hint: the default cells: [height][width]T = undefined works, then fill it with @splat(@splat('.')), or loop over the rows.

Show solution
const std = @import("std");
fn Grid(comptime T: type, comptime width: usize, comptime height: usize) type {
return struct {
cells: [height][width]T,
const Self = @This();
pub fn get(self: Self, x: usize, y: usize) T {
return self.cells[y][x];
}
pub fn set(self: *Self, x: usize, y: usize, value: T) void {
self.cells[y][x] = value;
}
};
}
pub fn main() void {
var grid: Grid(u8, 3, 2) = .{ .cells = @splat(@splat('.')) };
grid.set(1, 0, '#');
for (grid.cells) |row| std.debug.print("{s}\n", .{&row});
std.debug.print("({d}, {d}) is {c}\n", .{ 1, 0, grid.get(1, 0) });
}

Output:

.#.
...
(1, 0) is #

The outer @splat makes the array of rows, and the inner one fills each row with '.'. Grid(u8, 3, 2) knows its size at compile time, so it needs no allocator.

Write MinMax(comptime T: type) with fields min: T and max: T, a function init(first: T) Self that sets both to first, and add(self: *Self, value: T) void that updates them. Feed it 5, -2, 9, 3 as i32.

Hint: pub fn init(first: T) Self { return .{ .min = first, .max = first }; } has no self: you call it as MinMax(i32).init(5).

Show solution
const std = @import("std");
fn MinMax(comptime T: type) type {
return struct {
min: T,
max: T,
const Self = @This();
pub fn init(first: T) Self {
return .{ .min = first, .max = first };
}
pub fn add(self: *Self, value: T) void {
if (value < self.min) self.min = value;
if (value > self.max) self.max = value;
}
};
}
pub fn main() void {
var mm = MinMax(i32).init(5);
for ([_]i32{ -2, 9, 3 }) |v| mm.add(v);
std.debug.print("min {d}, max {d}\n", .{ mm.min, mm.max });
}

Output:

min -2, max 9

MinMax(i32).init(5) first builds the type, then calls the function inside it. Starting from a real first value means you don’t need to pick a “very big” starting number for min.

This code doesn’t compile. Find both problems and fix them.

const std = @import("std");
fn Counter(comptime T: type) type {
return struct {
count: T = 0,
const Self = @This();
pub fn bump(self: *Self) void {
self.count += 1;
}
};
}
pub fn main() void {
const c: Counter = .{};
c.bump();
std.debug.print("{d}\n", .{c.count});
}

Hint: one problem is in the type of c, the other in how it’s declared.

Show solution
const std = @import("std");
fn Counter(comptime T: type) type {
return struct {
count: T = 0,
const Self = @This();
pub fn bump(self: *Self) void {
self.count += 1;
}
};
}
pub fn main() void {
var c: Counter(u32) = .{};
c.bump();
std.debug.print("{d}\n", .{c.count});
}

Output:

1

Counter is the type function, so the variable needs Counter(u32). And bump changes the counter, so c must be a var, not a const.

  • A generic type is a function that returns a type: fn Stack(comptime T: type) type { return struct { ... }; }.
  • Name type functions in TitleCase, like types: Stack, ArrayList.
  • const Self = @This(); names the struct you’re inside, so methods can take self: *Self.
  • Type functions can take compile-time values too, like a capacity used as an array length.
  • The same arguments give the same type: Stack(i32) == Stack(i32).
  • Methods are only checked when called, so a method can require things only some T have.
  • std.ArrayList(T) and the other std collections are built exactly this way.

Next up: Zig Reflection, for looking inside a type at compile time: its fields, their names and their types.

Quick check

1. What does fn Stack(comptime T: type) type return?
2. Inside the struct returned by Stack, what does @This() give you?
3. Is Stack(i32) == Stack(i32) true?
4. Stack([]const u8) has a sum method that only works for numbers. When do you get an error?