Zig Interfaces
If you come from Java, C#, Go or Rust, you’ll look for an interface or trait keyword in Zig and you won’t find one. That doesn’t mean Zig can’t do “any type that can do X”. It means you build it yourself from parts you already know: tagged unions, anytype, and structs of function pointers. The standard library does this everywhere, so once you see the pattern, std.mem.Allocator and std.Io.Writer stop looking like magic. This page builds a tiny Shape interface two ways, then opens up the two interfaces you use every day.
Three ways to say “anything that can do X”
Section titled “Three ways to say “anything that can do X””Say you want one function that can report the area of a circle, a rectangle, or some shape you haven’t written yet. Zig gives you three tools, and each one fits a different situation:
| Tool | Who knows the list of types? | When the choice is made | Good for |
|---|---|---|---|
| Tagged union | You, all of them, up front | Run time, with a switch |
A fixed set of cases you own |
anytype |
Nobody, it’s open | Compile time | Generic helpers, maximum speed |
Vtable (ptr + function pointers) |
Nobody, it’s open | Run time | Plugins, allocators, writers, mixed lists |
We’ll go through them in that order, from the simplest to the one the standard library uses.
Option 1: a tagged union
Section titled “Option 1: a tagged union”If you know every shape your program will ever have, you don’t need an interface at all. Put them in a tagged union and switch on it:
const std = @import("std");
const Circle = struct { radius: f64,};
const Rect = struct { w: f64, h: f64,};
const Shape = union(enum) { circle: Circle, rect: Rect,
fn area(self: Shape) f64 { return switch (self) { .circle => |c| std.math.pi * c.radius * c.radius, .rect => |r| r.w * r.h, }; }};
pub fn main() void { const shapes = [_]Shape{ .{ .circle = .{ .radius = 1.0 } }, .{ .rect = .{ .w = 2.0, .h = 3.0 } }, }; var total: f64 = 0; for (shapes) |s| { std.debug.print("{t}: {d:.2}\n", .{ s, s.area() }); total += s.area(); } std.debug.print("total: {d:.2}\n", .{total});}Output:
circle: 3.14rect: 6.00total: 9.14This is the most “Zig” answer, and often the best one. Every shape lives inside the union itself, so there are no pointers to keep alive, an array of shapes is one flat block of memory, and the switch must cover every case: add a triangle and forget it in area, and the compiler stops you.
The catch is that the list is closed. Someone using your library can’t add their own shape without editing your union.
Option 2: anytype, checked at compile time
Section titled “Option 2: anytype, checked at compile time”The second tool is a parameter of type anytype. Zig makes a separate copy of the function for each type you call it with, and checks that the type has what the function uses:
const std = @import("std");
fn report(shape: anytype) void { std.debug.print("{s}: {d:.2}\n", .{ shape.name(), shape.area() });}
const Square = struct { side: f64, fn area(self: Square) f64 { return self.side * self.side; } fn name(_: Square) []const u8 { return "square"; }};
const Triangle = struct { base: f64, height: f64, fn area(self: Triangle) f64 { return self.base * self.height / 2; } fn name(_: Triangle) []const u8 { return "triangle"; }};
pub fn main() void { report(Square{ .side = 3 }); report(Triangle{ .base = 4, .height = 5 });}Output:
square: 9.00triangle: 10.00This is “duck typing”, but checked by the compiler: pass something without an area method and you get a compile error, not a crash. It’s as fast as it gets, because each copy of report calls the right area directly. Zig Generics covers anytype in depth.
Two limits, though. The interface is written down nowhere except in the function body, so readers have to look inside to see what’s needed. And you can’t put a Square and a Triangle in the same array, because they’re different types. For that, you need a single type that can stand for any shape at run time.
Option 3: the vtable pattern
Section titled “Option 3: the vtable pattern”Here’s the pattern the standard library uses. The interface is a small struct with two fields:
ptr: a pointer to the real object, with its type erased (*anyopaquemeans “a pointer to something, I won’t say what”).vtable: a pointer to a table of functions that know whatptrreally is.
const std = @import("std");
const Shape = struct { ptr: *anyopaque, vtable: *const VTable,
const VTable = struct { area: *const fn (ptr: *anyopaque) f64, name: *const fn (ptr: *anyopaque) []const u8, };
fn area(s: Shape) f64 { return s.vtable.area(s.ptr); }
fn name(s: Shape) []const u8 { return s.vtable.name(s.ptr); }};
const Circle = struct { radius: f64,
fn area(ptr: *anyopaque) f64 { const self: *Circle = @ptrCast(@alignCast(ptr)); return std.math.pi * self.radius * self.radius; }
fn name(_: *anyopaque) []const u8 { return "circle"; }
fn shape(self: *Circle) Shape { return .{ .ptr = self, .vtable = &.{ .area = area, .name = name } }; }};
const Rect = struct { w: f64, h: f64,
fn area(ptr: *anyopaque) f64 { const self: *Rect = @ptrCast(@alignCast(ptr)); return self.w * self.h; }
fn name(_: *anyopaque) []const u8 { return "rect"; }
fn shape(self: *Rect) Shape { return .{ .ptr = self, .vtable = &.{ .area = area, .name = name } }; }};
fn report(s: Shape) void { std.debug.print("{s}: {d:.2}\n", .{ s.name(), s.area() });}
pub fn main() void { var c: Circle = .{ .radius = 1.0 }; var r: Rect = .{ .w = 2.0, .h = 3.0 };
const shapes = [_]Shape{ c.shape(), r.shape() }; for (shapes) |s| report(s);
r.w = 10.0; report(shapes[1]);}Output:
circle: 3.14rect: 6.00rect: 30.00Let’s walk through it, because every vtable interface in Zig has the same parts:
- The interface type (
Shape) holdsptrandvtable, and has small methods likeareathat just call through the table. Code that uses shapes only ever seesShape. - Each implementation (
Circle,Rect) writes functions that take*anyopaqueand turn it back into the real type with@ptrCast(@alignCast(ptr)).@alignCastrestores the alignment information that*anyopaquedropped, and@ptrCastchanges the pointer type. In debug builds,@alignCastchecks the alignment for you. - A
shape()method packs a pointer to the object and its table into aShape. The&.{ .area = area, .name = name }table is built at compile time, so it’s a constant: one table per type, shared by every circle.
Look at the last line of output: we changed r.w after making the Shape, and the shape saw the change. That’s because Shape holds a pointer to r, not a copy. Which leads to the one rule you must remember.
Now you can put any shape in the same array, and someone else can write a Hexagon with its own shape() method without touching your code. The price is one extra pointer jump per call, and you must manage the lifetime of the object yourself.
std.mem.Allocator is exactly this
Section titled “std.mem.Allocator is exactly this”Here are the first lines of the real std.mem.Allocator, from the 0.17.1 source:
ptr: *anyopaque,vtable: *const VTable,
pub const VTable = struct { alloc: *const fn (*anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8, resize: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool, remap: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8, free: *const fn (*anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void,};Same shape as our Shape: a type-erased pointer and four functions. Everything you call on an allocator, alloc, free, create, dupe, print, is a normal method on Allocator that ends up calling one of those four. That’s why one std.mem.Allocator parameter can take an arena, the debug allocator, or a fixed buffer, as you saw in Zig Allocators.
Because it’s an ordinary struct, you can write your own. Here’s an allocator that wraps another one and counts what goes through it:
const std = @import("std");const Allocator = std.mem.Allocator;const Alignment = std.mem.Alignment;
const CountingAllocator = struct { child: Allocator, allocs: usize = 0, grows: usize = 0, frees: usize = 0,
fn allocator(self: *CountingAllocator) Allocator { return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free, }, }; }
fn alloc(ptr: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 { const self: *CountingAllocator = @ptrCast(@alignCast(ptr)); self.allocs += 1; return self.child.rawAlloc(len, alignment, ret_addr); }
fn resize(ptr: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool { const self: *CountingAllocator = @ptrCast(@alignCast(ptr)); self.grows += 1; return self.child.rawResize(memory, alignment, new_len, ret_addr); }
fn remap(ptr: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 { const self: *CountingAllocator = @ptrCast(@alignCast(ptr)); self.grows += 1; return self.child.rawRemap(memory, alignment, new_len, ret_addr); }
fn free(ptr: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void { const self: *CountingAllocator = @ptrCast(@alignCast(ptr)); self.frees += 1; self.child.rawFree(memory, alignment, ret_addr); }};
pub fn main(init: std.process.Init) !void { var counting: CountingAllocator = .{ .child = init.gpa }; const gpa = counting.allocator();
var list: std.ArrayList(u32) = .empty; for (0..100) |i| try list.append(gpa, @intCast(i)); list.deinit(gpa);
const text = try gpa.dupe(u8, "hello"); gpa.free(text);
std.debug.print("allocs: {d}, grows: {d}, frees: {d}\n", .{ counting.allocs, counting.grows, counting.frees });}Output:
allocs: 2, grows: 2, frees: 2The four functions follow the pattern from Circle: cast ptr back, do the counting, and pass the call on to the child allocator with rawAlloc, rawResize and so on (those call straight into the child’s vtable). The ArrayList needed one allocation and grew it twice to hold 100 numbers, and dupe added one more allocation. Wrappers like this are handy in tests, to check that a function doesn’t allocate more than you expect.
std.Io.Writer: the interface lives inside the struct
Section titled “std.Io.Writer: the interface lives inside the struct”std.Io.Writer is also a vtable interface, but with a twist. Instead of a ptr field, the Writer struct holds a buffer next to its vtable, and each implementation contains a Writer as one of its fields. That’s why you always write &file_writer.interface or &stdout.interface: you’re taking a pointer to the Writer that lives inside a bigger struct.
From the outside, it works like any interface. One function, three very different destinations:
const std = @import("std");
fn greet(w: *std.Io.Writer, name: []const u8) !void { try w.print("Hello, {s}!\n", .{name});}
pub fn main(init: std.process.Init) !void { // 1. stdout var out_buf: [256]u8 = undefined; var stdout = std.Io.File.stdout().writer(init.io, &out_buf); try greet(&stdout.interface, "terminal"); try stdout.interface.flush();
// 2. a fixed buffer in memory var mem_buf: [64]u8 = undefined; var fixed: std.Io.Writer = .fixed(&mem_buf); try greet(&fixed, "buffer"); std.debug.print("buffer holds: {s}", .{fixed.buffered()});
// 3. a writer that grows with an allocator var growing: std.Io.Writer.Allocating = .init(init.gpa); defer growing.deinit(); try greet(&growing.writer, "heap"); std.debug.print("heap holds: {s}", .{growing.written()});}Output:
Hello, terminal!buffer holds: Hello, buffer!heap holds: Hello, heap!greet takes *std.Io.Writer and has no idea where its bytes go. That’s what makes code that writes output easy to test: pass a fixed or allocating writer in a test, and the real stdout in your program. Zig Readers & Writers shows more of this.
Writing your own writer
Section titled “Writing your own writer”To make your own writer, you put a std.Io.Writer field in your struct and give it a drain function. The writer collects bytes in its buffer, and calls drain when the buffer is full or when you flush. Inside drain, the builtin @fieldParentPtr gets you from the pointer to the writer field back to the struct around it.
Here’s a writer that throws the text away but counts the lines:
const std = @import("std");
const LineCounter = struct { lines: usize = 0, writer: std.Io.Writer,
fn init(buffer: []u8) LineCounter { return .{ .writer = .{ .vtable = &.{ .drain = drain }, .buffer = buffer } }; }
fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { const self: *LineCounter = @alignCast(@fieldParentPtr("writer", w)); // First the bytes waiting in the buffer... self.lines += std.mem.countScalar(u8, w.buffered(), '\n'); w.end = 0; // ...then every slice in `data`. The last one is repeated `splat` times. var written: usize = 0; for (data[0 .. data.len - 1]) |bytes| { self.lines += std.mem.countScalar(u8, bytes, '\n'); written += bytes.len; } const last = data[data.len - 1]; self.lines += std.mem.countScalar(u8, last, '\n') * splat; written += last.len * splat; return written; }};
fn poem(w: *std.Io.Writer) !void { try w.writeAll("Roses are red\n"); try w.writeAll("Zig is too\n"); try w.print("{d} lines {s}\n", .{ 3, "for you" });}
pub fn main() !void { var buf: [16]u8 = undefined; var counter: LineCounter = .init(&buf); try poem(&counter.writer); try counter.writer.flush(); std.debug.print("lines: {d}\n", .{counter.lines});}Output:
lines: 3drain has to handle two things: the bytes already sitting in the buffer (w.buffered(), then reset w.end to 0 to empty it), and the new data. data is a list of slices, and the last slice counts splat times. That lets callers write “50 spaces” without making a 50-byte string. Return how many bytes of data you took. The Writer source documents these rules on the VTable and has small implementations to copy from, like Discarding.
Which one should you pick?
Section titled “Which one should you pick?”- Start with a tagged union when you own every case. It’s the simplest, it’s fast, and the compiler checks you handled everything.
- Use
anytypefor small generic helpers where each call site knows its type, and you don’t need a mixed list. - Use a vtable when the set must stay open (users bring their own types) or when you need to store different types side by side and choose at run time. That’s why allocators, readers and writers use it.
Don’t build a vtable “just in case”. It’s more code, and the lifetime rule above is a real source of bugs.
Practice
Section titled “Practice”1. Add a triangle to the union
Section titled “1. Add a triangle to the union”Add a triangle with base and height to the tagged-union Shape from Option 1, and print the area of one triangle with base = 4 and height = 5.
Hint: add a Triangle struct, a triangle: Triangle field in the union, and a new prong in the switch. Try leaving the prong out first, to see the compiler complain.
Show solution
const std = @import("std");
const Rect = struct { w: f64, h: f64 };const Triangle = struct { base: f64, height: f64 };
const Shape = union(enum) { rect: Rect, triangle: Triangle,
fn area(self: Shape) f64 { return switch (self) { .rect => |r| r.w * r.h, .triangle => |t| t.base * t.height / 2, }; }};
pub fn main() void { const t: Shape = .{ .triangle = .{ .base = 4, .height = 5 } }; std.debug.print("{t}: {d:.2}\n", .{ t, t.area() });}Output:
triangle: 10.00Without the .triangle prong, the switch isn’t exhaustive and the program doesn’t compile. That check is the big win of tagged unions.
2. Count bytes with Discarding
Section titled “2. Count bytes with Discarding”The standard library has a writer that throws everything away and only counts: std.Io.Writer.Discarding. Use it to find out how many bytes greet(w, "Zig") from the writer section would print, without printing anything.
Hint: var buf: [64]u8 = undefined; var d: std.Io.Writer.Discarding = .init(&buf);, pass &d.writer, then read d.fullCount() (it includes bytes still in the buffer).
Show solution
const std = @import("std");
fn greet(w: *std.Io.Writer, name: []const u8) !void { try w.print("Hello, {s}!\n", .{name});}
pub fn main() !void { var buf: [64]u8 = undefined; var d: std.Io.Writer.Discarding = .init(&buf); try greet(&d.writer, "Zig"); std.debug.print("greet would print {d} bytes\n", .{d.fullCount()});}Output:
greet would print 12 bytesDiscarding is built just like our LineCounter: a struct with a writer: std.Io.Writer field and a drain that counts. “Hello, Zig!” plus the newline is 12 bytes.
3. A square for the vtable Shape
Section titled “3. A square for the vtable Shape”Add a Square with one field, side, to the vtable example from Option 3, so this works: var sq: Square = .{ .side = 3 }; report(sq.shape());
Hint: copy Rect and change the fields and the area formula. Keep the @ptrCast(@alignCast(ptr)) line.
Show solution
const std = @import("std");
const Shape = struct { ptr: *anyopaque, vtable: *const VTable,
const VTable = struct { area: *const fn (ptr: *anyopaque) f64, name: *const fn (ptr: *anyopaque) []const u8, };
fn area(s: Shape) f64 { return s.vtable.area(s.ptr); }
fn name(s: Shape) []const u8 { return s.vtable.name(s.ptr); }};
const Square = struct { side: f64,
fn area(ptr: *anyopaque) f64 { const self: *Square = @ptrCast(@alignCast(ptr)); return self.side * self.side; }
fn name(_: *anyopaque) []const u8 { return "square"; }
fn shape(self: *Square) Shape { return .{ .ptr = self, .vtable = &.{ .area = area, .name = name } }; }};
fn report(s: Shape) void { std.debug.print("{s}: {d:.2}\n", .{ s.name(), s.area() });}
pub fn main() void { var sq: Square = .{ .side = 3 }; report(sq.shape());}Output:
square: 9.00Shape and report didn’t change at all. That’s the open set in action: a new type joins the interface by providing the functions, nothing else.
- Zig has no interface keyword. You pick from three tools instead.
- A tagged union is the simplest choice when you know every case: fast, flat, and the
switchmust be exhaustive. anytypegives compile-time duck typing: very fast, but no mixed lists.- A vtable interface is a struct with a type-erased
ptr: *anyopaqueand avtableof function pointers. Implementations cast back with@ptrCast(@alignCast(ptr)). std.mem.Allocatoris exactly that pattern.std.Io.Writerkeeps the interface inside the implementation and uses@fieldParentPtr.- The object must outlive the interface, and you must never copy a
WriterorReaderout of its struct.
Next up: Zig Design Patterns, the everyday shapes of Zig code: init/deinit, options structs, and errors that carry details.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: @fieldParentPtr: the builtin behind
std.Io.Writerimplementations. - std.mem.Allocator source (0.17.1): the real vtable, with a doc comment on every function.
- std.Io.Writer source (0.17.1): the rules for
drain, plusDiscarding,Allocatingandfixed. - Zig 0.15.1 release notes: Writergate: why the buffer moved into the interface.
- Zig Interfaces (openmymind.net): a community walk-through of the vtable pattern, written for an older Zig, so check the code against 0.17.