An interface defines operations that callers can use without depending on the details of a particular implementation. A writer, for example, can send bytes to a file, a network connection, or a buffer while exposing a common way to write. section 3.2.3
In Zig, the interface pattern can make the machinery explicit. A minimal writer holds an opaque context pointer and a pointer to a table of functions. Its writeAll method calls the table’s write_bytes function, passing both the context and the bytes. The implementation behind that function determines where the bytes go. section 3.2.3
Listing 3.4 What is an interface?
const WriterInterface = struct {
context: *const anyopaque, #1
vtable: *const VTable, #2
const VTable = struct {
write_bytes: *const fn(
context: *const anyopaque,
bytes: []const u8,
),
};
// methods like print can go here!
fn writeAll(self: @This(), bytes: []const u8) void {
self.vtable.write_bytes(self.context, bytes);
}
}
Inspect the context pointer, function table, and writeAll dispatch in a stripped-down writer interface. section 3.2.3
The context uses *const anyopaque because the interface does not specify the pointed-to data’s type. Using that data requires a cast to its actual type; the details of that cast are a separate topic. This is boilerplate, but it makes visible work that other language features can hide. section 3.2.3
Listing 3.3 Hello world, in context
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const stdout_file = std.Io.File.stdout(); #1
var stdout_buffer: [1024]u8 = undefined; #2
var stdout_writer = stdout_file.writer(io, &stdout_buffer); #3
const stdout = &stdout_writer.interface; #4
try stdout.writeAll("All your codebase belong to us yet again!"); #5
try stdout.flush(); #6
}
See a file writer supply its interface to stdout output, with an explicit buffer and flush. section 3.2.3
Designing an HTTP interface
An interface can also mean the functionality a server promises to clients. For a word ladder, GET / returns the page, POST /ladder checks a ladder, and GET /first provides a starting word. Validation results become an HTTP 200 response or a 400 response with an error message. section 4.2.5
Interfaces also give modules boundaries: self-contained parts of a project interact through defined interfaces rather than treating the whole project as one undivided unit. section 6.3.1












