To print to stdout, Zig can build a std.Io.Writer around a file and a buffer. The writer is a flexible interface for output destinations across the standard library, including files, string building, formatting, and networking. section 1.6.2
Listing 1.2 All your codebase still belong to us
const std = @import("std");
pub fn main(init: std.process.Init) !void { #1
const io = init.io;
const stdout = std.Io.File.stdout(); #2
var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = stdout.writer(io, &stdout_buffer); #3
const writer = &stdout_writer.interface; #3
try writer.print("All your codebase still belong to us!\n", .{}); #4
try writer.flush(); #5
}
A stdout writer uses the I/O instance from process.Init, a 1024-byte buffer, and the file writer’s interface. Both print and flush use try because output can fail. section 1.6.2
The interface separates a writer’s operations from its underlying destination. Different implementations can write to a file, network connection, buffer, or another output you implement. The pattern resembles Zig’s allocator interfaces. 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);
}
}
This simplified interface model pairs an opaque context pointer with a vtable of function pointers. writeAll delegates to write_bytes, passing the context and bytes; the model illustrates the pattern rather than the full standard-library implementation. section 3.2.3
The anyopaque pointer avoids specifying the context’s data type in generic code. Using its actual data requires a cast; that detail is left for later. A writer is also optional: raw syscalls, libc’s printf, or standard-library all-in-one operations are alternatives when they fit the job better. section 3.2.3 section 1.6.2
