Zig Design Patterns
Read enough Zig code, including the standard library, and you’ll notice the same few shapes over and over. They aren’t rules of the language. They’re habits the community settled on because they make memory, errors and configuration easy to follow. This page shows the five you’ll meet most often, each with a small program, so your own code looks familiar to other Zig developers and theirs looks familiar to you.
init and deinit: who sets up, who cleans up
Section titled “init and deinit: who sets up, who cleans up”Zig has no constructors or destructors. Instead, a type that needs setting up gets an init function, and a type that holds resources gets a deinit function. The caller pairs them with defer, right next to each other:
const std = @import("std");
const Inventory = struct { gpa: std.mem.Allocator, items: std.StringHashMapUnmanaged(u32),
pub fn init(gpa: std.mem.Allocator) Inventory { return .{ .gpa = gpa, .items = .empty }; }
pub fn deinit(self: *Inventory) void { var it = self.items.keyIterator(); while (it.next()) |key| self.gpa.free(key.*); self.items.deinit(self.gpa); self.* = undefined; }
pub fn add(self: *Inventory, name: []const u8, amount: u32) !void { if (self.items.getPtr(name)) |n| { n.* += amount; return; } const owned = try self.gpa.dupe(u8, name); errdefer self.gpa.free(owned); try self.items.put(self.gpa, owned, amount); }
pub fn count(self: Inventory, name: []const u8) u32 { return self.items.get(name) orelse 0; }};
pub fn main(init: std.process.Init) !void { var inv: Inventory = .init(init.gpa); defer inv.deinit();
try inv.add("apple", 3); try inv.add("pear", 1); try inv.add("apple", 2);
std.debug.print("apples: {d}, pears: {d}, plums: {d}\n", .{ inv.count("apple"), inv.count("pear"), inv.count("plum"), });}Output:
apples: 5, pears: 1, plums: 0A few habits are packed in here:
var inv: Inventory = .init(init.gpa);The type goes on the left, and.init(...)on the right is looked up inside that type. This is called a decl literal, and it’s why you see= .empty,= .initand= .{}all over Zig code.std.ArrayList(u8) = .emptyis the same trick with a constant instead of a function.initcan’t fail here, so it returnsInventory, not!Inventory. If setting up needs memory or a file,initreturns an error union and you writetry.deinittakes*Inventory(a pointer), because it changes the value. It frees in the reverse order of setting up: first the keys the map owns, then the map itself.self.* = undefined;at the end ofdeinitis a common Zig habit. In debug builds it fills the struct with0xaabytes, so if someone uses the inventory afterdeinit, they get obviously broken values instead of something that almost works.errdefer self.gpa.free(owned);inadd: ifputfails, the copy of the name doesn’t leak. Zig errdefer covers this.
Pass the allocator
Section titled “Pass the allocator”If a function needs heap memory, it takes an allocator as a parameter. It doesn’t reach for a global one. That single habit is why Zig code is easy to test and easy to reason about: you can see from the signature that a function allocates, and the caller decides where the memory comes from.
const std = @import("std");
/// Joins `words` with a single space between them./// The caller owns the returned memory and must free it with `gpa`.fn joinWords(gpa: std.mem.Allocator, words: []const []const u8) ![]u8 { return std.mem.join(gpa, " ", words);}
test "joinWords" { const gpa = std.testing.allocator; const text = try joinWords(gpa, &.{ "pass", "the", "allocator" }); defer gpa.free(text); try std.testing.expectEqualStrings("pass the allocator", text);}
test "joinWords with an arena" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const text = try joinWords(arena.allocator(), &.{ "no", "free", "needed" }); try std.testing.expectEqualStrings("no free needed", text);}Output:
1/2 main.test.joinWords...OK2/2 main.test.joinWords with an arena...OKAll 2 tests passed.The same function works with the testing allocator (which fails the test if you leak) and with an arena (where nobody frees anything). Two more habits:
- Say who owns the result in a doc comment. “The caller owns the returned memory” is the standard phrase. Zig Lifetimes & Ownership explains why it matters.
- Name the parameter for what it is.
gpasays “free what you get”,arenasays “don’t bother”. The standard library uses those names too.
Store it, or ask for it every time?
Section titled “Store it, or ask for it every time?”Inventory above stores its allocator in a field. The standard library’s containers mostly do the opposite: std.ArrayList and std.StringHashMapUnmanaged don’t store one, so you pass it to every call that might allocate (list.append(gpa, x), list.deinit(gpa)). That keeps the struct smaller and makes every allocating call visible.
Both are fine. A good rule: low-level containers ask for the allocator each time; a bigger “thing” in your program, like a game world or a server, usually stores it once in init so its methods stay short. Just never mix allocators: free with the same one you allocated with.
Options structs with default values
Section titled “Options structs with default values”Zig has no named arguments and no default argument values. What it has instead is better than it sounds: a struct whose fields have defaults, passed as the last parameter.
const std = @import("std");
const Options = struct { port: u16 = 8080, host: []const u8 = "127.0.0.1", max_connections: u32 = 100, verbose: bool = false,};
fn startServer(name: []const u8, options: Options) void { std.debug.print("{s}: {s}:{d}, max {d}, verbose={}\n", .{ name, options.host, options.port, options.max_connections, options.verbose, });}
pub fn main() void { startServer("defaults", .{}); startServer("custom port", .{ .port = 3000 }); startServer("chatty", .{ .verbose = true, .max_connections = 5 });}Output:
defaults: 127.0.0.1:8080, max 100, verbose=falsecustom port: 127.0.0.1:3000, max 100, verbose=falsechatty: 127.0.0.1:8080, max 5, verbose=trueCallers write .{} for “all defaults” and name only the fields they want to change, in any order. Adding a new option later doesn’t break any existing call, as long as it has a default. You’ve been using this pattern all along: cwd.createFile(io, "notes.txt", .{}), address.listen(io, .{ .reuse_address = true }) and b.standardOptimizeOption(.{}) are all options structs. The language reference on default field values has the details.
Builders: you mostly don’t need one
Section titled “Builders: you mostly don’t need one”In Java or Rust you often build things with a chain like Request.new(url).post().timeout(1000). You can do that in Zig: each method takes the struct by value, changes a copy, and returns it.
const std = @import("std");
const Request = struct { url: []const u8, method: []const u8 = "GET", timeout_ms: u32 = 5000, retries: u8 = 0,
fn init(url: []const u8) Request { return .{ .url = url }; }
fn post(self: Request) Request { var r = self; r.method = "POST"; return r; }
fn timeout(self: Request, ms: u32) Request { var r = self; r.timeout_ms = ms; return r; }
fn retry(self: Request, times: u8) Request { var r = self; r.retries = times; return r; }};
pub fn main() void { const req = Request.init("https://example.com/api").post().timeout(1000).retry(3); std.debug.print("{s} {s}, timeout {d} ms, {d} retries\n", .{ req.method, req.url, req.timeout_ms, req.retries });
// The same thing as an options struct: const same: Request = .{ .url = "https://example.com/api", .method = "POST", .timeout_ms = 1000, .retries = 3 }; std.debug.print("{s} {s}, timeout {d} ms, {d} retries\n", .{ same.method, same.url, same.timeout_ms, same.retries });}Output:
POST https://example.com/api, timeout 1000 ms, 3 retriesPOST https://example.com/api, timeout 1000 ms, 3 retriesBoth lines build the same request, and the second one needed no extra code at all. That’s why chained builders are rare in Zig: a struct literal with default fields already does the job. Reach for a builder only when building is more than filling in fields, for example when each step checks something, allocates, or adds to a list. The build system is a real example: b.addExecutable(...), exe.root_module.addImport(...) and b.installArtifact(exe) build up a graph step by step, as you saw in Zig Build System.
Errors that carry details: the diagnostics pattern
Section titled “Errors that carry details: the diagnostics pattern”Zig errors are just names, like error.BadNumber. They can’t carry a line number or the text that was wrong. That’s on purpose (errors stay cheap and can’t leak memory), but a message like “BadNumber” isn’t much help to a user. The standard answer is the diagnostics pattern: the caller passes an optional pointer to a struct, and the function fills it in before it returns an error.
const std = @import("std");
const Config = struct { width: u32 = 800, height: u32 = 600,};
/// Filled in when parsing fails, so the caller can say *where*.const Diagnostics = struct { line_number: usize = 0, line: []const u8 = "",};
const ParseError = error{ MissingEquals, UnknownKey, BadNumber };
fn parseConfig(text: []const u8, diag: ?*Diagnostics) ParseError!Config { var config: Config = .{}; var lines = std.mem.splitScalar(u8, text, '\n'); var line_number: usize = 0; while (lines.next()) |line| { line_number += 1; if (line.len == 0) continue; // Remember where we are, in case this line fails. if (diag) |d| d.* = .{ .line_number = line_number, .line = line };
const key, const value = std.mem.cutScalar(u8, line, '=') orelse return error.MissingEquals; const field: *u32 = if (std.mem.eql(u8, key, "width")) &config.width else if (std.mem.eql(u8, key, "height")) &config.height else return error.UnknownKey; field.* = std.fmt.parseInt(u32, value, 10) catch return error.BadNumber; } return config;}
pub fn main() void { const inputs = [_][]const u8{ "width=1024\nheight=768", "width=1024\nheight=lots", "width=1024\ncolor=blue", "width 1024", }; for (inputs) |text| { var diag: Diagnostics = .{}; if (parseConfig(text, &diag)) |config| { std.debug.print("ok: {d}x{d}\n", .{ config.width, config.height }); } else |err| { std.debug.print("error: {t} on line {d}: \"{s}\"\n", .{ err, diag.line_number, diag.line }); } }}Output:
ok: 1024x768error: BadNumber on line 2: "height=lots"error: UnknownKey on line 2: "color=blue"error: MissingEquals on line 1: "width 1024"How it fits together:
- The function still returns a normal error union, so
tryandcatchwork as usual. The error name says what went wrong. - The
?*Diagnosticsparameter says where and with what. It’s optional: a caller that only cares whether parsing worked passesnull. diag.lineis a slice of the input text, so it’s only valid whiletextis. If the details need to outlive the input, copy them with an allocator.
The standard library uses this exact shape: std.json has a Diagnostics type that reports the line and column of a JSON error, and so does std.zon.parse. Zig Custom Errors shows more ways to design your error sets.
Practice
Section titled “Practice”1. An options struct
Section titled “1. An options struct”Write banner(text, options) that prints text centered in a line of fill characters. The options are width (default 20) and fill (default '*'). Call it three ways: with all defaults, with fill = '=', and with width = 30, fill = '-'.
Hint: padding on each side is (options.width -| text.len) / 2. The -| operator subtracts but stops at 0 instead of overflowing.
Show solution
const std = @import("std");
const BannerOptions = struct { width: usize = 20, fill: u8 = '*',};
fn banner(text: []const u8, options: BannerOptions) void { const pad = (options.width -| text.len) / 2; for (0..pad) |_| std.debug.print("{c}", .{options.fill}); std.debug.print("{s}", .{text}); for (0..pad) |_| std.debug.print("{c}", .{options.fill}); std.debug.print("\n", .{});}
pub fn main() void { banner(" hi ", .{}); banner(" zig ", .{ .fill = '=' }); banner(" wide ", .{ .width = 30, .fill = '-' });}Output:
******** hi ********======= zig =======------------ wide ------------Each call names only what it changes. If you later add a newline: bool = true option, none of these calls need to change.
2. A port parser with details
Section titled “2. A port parser with details”Write parsePort(text, diag) that returns a u16 port or error.InvalidPort. Port 0 is also invalid. When it fails, it should store the bad text in diag.bad_text (if diag isn’t null). Try it with "8080", "eighty", "0" and "70000", and once with null.
Hint: std.fmt.parseInt(u16, text, 10) already fails for "70000", because it doesn’t fit in a u16.
Show solution
const std = @import("std");
const PortDiagnostics = struct { bad_text: []const u8 = "",};
fn parsePort(text: []const u8, diag: ?*PortDiagnostics) error{InvalidPort}!u16 { const port = std.fmt.parseInt(u16, text, 10) catch { if (diag) |d| d.bad_text = text; return error.InvalidPort; }; if (port == 0) { if (diag) |d| d.bad_text = text; return error.InvalidPort; } return port;}
pub fn main() void { for ([_][]const u8{ "8080", "eighty", "0", "70000" }) |text| { var diag: PortDiagnostics = .{}; if (parsePort(text, &diag)) |port| { std.debug.print("port {d}\n", .{port}); } else |err| { std.debug.print("{t}: \"{s}\"\n", .{ err, diag.bad_text }); } } // Callers who don't care about details pass null. const quiet = parsePort("443", null) catch 0; std.debug.print("quiet: {d}\n", .{quiet});}Output:
port 8080InvalidPort: "eighty"InvalidPort: "0"InvalidPort: "70000"quiet: 443The error set stays tiny (one name), and the details travel separately. if (diag) |d| unwraps the optional pointer only when the caller gave one.
- Types that need setup get
init; types that hold resources getdeinit. Pair them withdeferon the next line. - Decl literals like
.init(gpa)and.emptylook the name up in the type on the left. - Pass the allocator to anything that allocates, and document who owns the result.
- Options structs with default fields replace named and default arguments. Callers write
.{}or name only what they change. - Builders are rarely needed: a struct literal with defaults usually does the same job.
- For errors with details, use the diagnostics pattern: an error union for what, plus an optional
?*Diagnosticsfor where.
Next up: Zig Performance, how to measure before you optimize, and the changes that usually make the biggest difference.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Default Field Values: the feature behind options structs.
- Zig language reference: Style Guide: naming rules the patterns on this page follow.
- TigerBeetle’s TIGER_STYLE.md: the coding rules of a large Zig project, including how they name allocators and set things up.
- Learning Zig (openmymind.net): a community guide with more init/deinit and allocator examples, written for an older Zig.