Zig Io Interface
By now you’ve typed init.io dozens of times: to print to stdout, to open files, to run other programs. This page explains what that io value really is, and why Zig makes you pass it around. The short version is that io does for input and output what an allocator does for memory. Once that clicks, a lot of Zig 0.16 and 0.17 code starts to look less strange.
Everything that touches the outside world takes io
Section titled “Everything that touches the outside world takes io”Since Zig 0.16, the standard library has one rule: anything that might wait on the outside world or give a different answer each time goes through a std.Io value. That covers:
- files, folders, stdin, stdout and stderr
- the network
- starting other programs
- sleeping and reading clocks
- random numbers from the system
- running tasks at the same time (async), and the locks that keep them safe
Here are a few of those in one small program:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const io = init.io;
try std.Io.File.stdout().writeStreamingAll(io, "Taking a short nap...\n");
const start = std.Io.Timestamp.now(io, .awake); try io.sleep(.fromMilliseconds(300), .awake); const ms = start.untilNow(io, .awake).toMilliseconds();
std.debug.print("Slept for about {d} ms\n", .{@divTrunc(ms, 100) * 100});}Output:
Taking a short nap...Slept for about 300 msWriting to stdout, reading the clock and sleeping all take io. (The .awake argument picks a clock that only moves forward, the right choice for measuring how long something took. @divTrunc(ms, 100) * 100 just rounds down to a tidy number, because the real time is a few milliseconds more on every run.)
And here’s what does not need io: plain computation, allocating memory (that’s the allocator’s job), and std.debug.print, which is a debugging tool that writes straight to stderr.
Why an interface? Think of allocators
Section titled “Why an interface? Think of allocators”You’ve already met this idea. In Zig, a function that needs memory doesn’t grab it from a hidden global; it takes a std.mem.Allocator parameter, and the caller decides which allocator to use (Zig Allocators covers this). std.Io is the same deal for I/O. The 0.16.0 release notes put the rule like this: anything that potentially blocks or introduces nondeterminism belongs to the I/O interface.
That buys you three things.
1. You can see what a function does from its signature. If a function takes io, it might touch files, the network or the clock. If it doesn’t, it can’t. In most languages any function can quietly open a file.
2. main decides how I/O happens, and library code doesn’t care. The io you get from init.io today is built on plain operating system threads. The Zig team is also working on implementations built on things like Linux’s io_uring, where lots of tasks can wait without each needing its own thread. Code that takes an io parameter works with any of them without changes. You swap the implementation in one place, like swapping an allocator.
3. No “colored” functions. If you’ve used JavaScript, Python or Rust, you know that once a function is async, everything calling it has to be async too, and you end up with two versions of every library. Old Zig had async and await keywords with a similar problem, and they were taken out of the language. In Zig 0.16 and later, a function just takes io. The same function can be called normally, or started in the background with io.async, which is the topic of Zig Async & Futures.
Getting an io: from main
Section titled “Getting an io: from main”The normal way is the one you’ve been using. Give main an init: std.process.Init parameter, and init.io is ready to go:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const io = init.io; var roll: [1]u8 = undefined; io.random(&roll); std.debug.print("You rolled a {d}\n", .{roll[0] % 6 + 1});}The number changes every run, of course. (Taking a byte modulo 6 is slightly uneven, which is fine for a toy dice roll but not for anything serious.)
Behind the scenes, Zig’s startup code creates a std.Io.Threaded before your main runs, hands you its io, and cleans it up after main returns. Threaded does I/O the classic way: a read is a real read system call that waits, and background tasks run on a pool of threads. The release notes call it feature-complete and well-tested, and it’s the one you’ll use almost all the time.
Pass it down like an allocator
Section titled “Pass it down like an allocator”Functions that need I/O take an io: std.Io parameter. By convention it goes first, or right after self in a method:
const std = @import("std");
fn countdown(io: std.Io, from: u32) !void { var n = from; while (n > 0) : (n -= 1) { std.debug.print("{d}...\n", .{n}); try io.sleep(.fromMilliseconds(100), .awake); } std.debug.print("liftoff!\n", .{});}
pub fn main(init: std.process.Init) !void { try countdown(init.io, 3);}Output:
3...2...1...liftoff!std.Io is tiny (two pointers), so you pass it by value, never as *std.Io. When many functions in one part of your program need it, put it in a struct together with the allocator:
const std = @import("std");
const App = struct { io: std.Io, gpa: std.mem.Allocator,
fn saveScore(app: App, score: u32) !void { const text = try app.gpa.print("score={d}\n", .{score}); defer app.gpa.free(text); try std.Io.Dir.cwd().writeFile(app.io, .{ .sub_path = "score.txt", .data = text }); }};
pub fn main(init: std.process.Init) !void { const app: App = .{ .io = init.io, .gpa = init.gpa }; try app.saveScore(42);
const saved = try std.Io.Dir.cwd().readFileAlloc(init.io, "score.txt", init.gpa, .limited(100)); defer init.gpa.free(saved); std.debug.print("{s}", .{saved});
try std.Io.Dir.cwd().deleteFile(init.io, "score.txt");}Output:
score=42Making an io yourself
Section titled “Making an io yourself”Sometimes there’s no init around: a main with no parameters, or a small tool you’re upgrading from older Zig. You can make a Threaded yourself. The quickest version is single-threaded:
const std = @import("std");
pub fn main() !void { var threaded: std.Io.Threaded = .init_single_threaded; const io = threaded.io();
try std.Io.File.stdout().writeStreamingAll(io, "made my own io\n");}Output:
made my own ioThat’s fine for plain reading and writing. It can’t run tasks at the same time, though, so anything that needs real concurrency fails with error.ConcurrencyUnavailable (Zig Async & Futures shows it). For the full version, give it an allocator for its task bookkeeping and clean it up:
const std = @import("std");
pub fn main() !void { var threaded: std.Io.Threaded = .init(std.heap.smp_allocator, .{}); defer threaded.deinit(); const io = threaded.io();
try io.sleep(.fromMilliseconds(50), .awake); std.debug.print("full Threaded io works too\n", .{});}Output:
full Threaded io works tooThis is close to what Zig’s startup code does for init.io (it passes init.gpa instead of smp_allocator). The release notes describe the single-threaded trick as a stopgap, so in real programs prefer taking init in main and passing init.io down.
Testing code that does I/O
Section titled “Testing code that does I/O”Here’s where passing io around really pays off. In tests, use std.testing.io, just like you use std.testing.allocator for memory. It’s a ready-to-use Threaded io that only exists while tests run.
There’s a second trick too. std.Io.failing is a ready-made “broken world”: every file is missing, the disk is full and every pipe is closed. Hand it to your function to check that errors come out the way you expect:
const std = @import("std");
fn loadConfig(io: std.Io, gpa: std.mem.Allocator) ![]u8 { return std.Io.Dir.cwd().readFileAlloc(io, "app.conf", gpa, .limited(4096));}
fn saveNote(io: std.Io, text: []const u8) !void { try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = "note.txt", .data = text });}
test "a missing config file is reported" { const result = loadConfig(std.Io.failing, std.testing.allocator); try std.testing.expectError(error.FileNotFound, result);}
test "a full disk is reported" { try std.testing.expectError(error.NoSpaceLeft, saveNote(std.Io.failing, "buy milk\n"));}
test "sleeping works in tests" { try std.testing.io.sleep(.fromMilliseconds(10), .awake);}Output:
1/3 main.test.a missing config file is reported...OK2/3 main.test.a full disk is reported...OK3/3 main.test.sleeping works in tests...OKAll 3 tests passed.No temporary files, no unplugging network cables. Because the function takes io instead of reaching for a global, you can test the error paths in a few lines.
What’s inside an io
Section titled “What’s inside an io”If you open lib/std/Io.zig, the whole value is two fields:
userdata: ?*anyopaque,vtable: *const VTable,vtable points at a table of functions (one for opening files, one for sleeping, one for starting async tasks, and so on), and userdata points at the implementation’s own state, like the Threaded struct. When you call io.sleep(...), it looks up the sleep function in the table and calls it with userdata. std.mem.Allocator has exactly the same shape (ptr and vtable). Zig Interfaces shows how to build this pattern yourself.
The standard library in 0.17.1 ships these implementations:
| Implementation | What it is | Status |
|---|---|---|
std.Io.Threaded |
Blocking system calls, a thread pool for tasks | The default; what init.io uses |
std.Io.Evented |
Green threads (many tasks on few threads) | Experimental. On Linux it maps to Io.Uring, which didn’t even compile in 0.17.1 when we tried it |
std.Io.Uring, Kqueue, Dispatch |
Built on io_uring, kqueue, Grand Central Dispatch |
Work in progress |
std.Io.failing |
A world where everything fails | For tests |
std.testing.io |
A Threaded set up for tests |
For tests |
So, honestly: today you’ll use Threaded, and the others are where the design is heading. That’s fine, because your code doesn’t change when they’re ready.
Upgrading older code
Section titled “Upgrading older code”If you find Zig code from before 0.16 online, these are the most common changes. All of them come from the 0.16.0 release notes:
| Old (0.15 and earlier) | Now |
|---|---|
std.fs.cwd() |
std.Io.Dir.cwd(), and most calls take io |
file.close() |
file.close(io) |
std.Thread.sleep(ns) |
io.sleep(.fromMilliseconds(ms), .awake) |
std.time.timestamp(), std.time.Timer |
std.Io.Timestamp.now(io, clock) |
std.crypto.random.bytes(&buf) |
io.random(&buf) |
std.Thread.Mutex, WaitGroup |
std.Io.Mutex, std.Io.Group |
std.Thread.Pool |
removed: use io.async or std.Io.Group |
Most of the work is adding io as a parameter and following the compiler’s errors.
Practice
Section titled “Practice”1. A slow printer
Section titled “1. A slow printer”Write fn slowPrint(io: std.Io, text: []const u8) !void that prints each character of text with std.debug.print, sleeping 20 ms after each one, then a newline. Call it from main with "hello".
Hint: loop with for (text) |c|, print with {c}, then try io.sleep(.fromMilliseconds(20), .awake);.
Show solution
const std = @import("std");
fn slowPrint(io: std.Io, text: []const u8) !void { for (text) |c| { std.debug.print("{c}", .{c}); try io.sleep(.fromMilliseconds(20), .awake); } std.debug.print("\n", .{});}
pub fn main(init: std.process.Init) !void { try slowPrint(init.io, "hello");}Output:
helloIn a terminal you can watch the letters appear one by one. The function takes io because sleeping goes through the I/O interface.
2. Test it
Section titled “2. Test it”Add a test for slowPrint that calls it with std.testing.io and the text "ok".
Hint: a test is test "name" { ... }, and you call the function with try.
Show solution
const std = @import("std");
fn slowPrint(io: std.Io, text: []const u8) !void { for (text) |c| { std.debug.print("{c}", .{c}); try io.sleep(.fromMilliseconds(20), .awake); } std.debug.print("\n", .{});}
test "slowPrint runs" { try slowPrint(std.testing.io, "ok");}Output:
1/1 main.test.slowPrint runs...okOKAll 1 tests passed.std.testing.io is the test-time io, the same way std.testing.allocator is the test-time allocator. The ok lands in the middle of the test runner’s own line because both write to stderr.
3. Simulate a broken world
Section titled “3. Simulate a broken world”Write fn appendLog(io: std.Io, line: []const u8) !void that writes line to log.txt with std.Io.Dir.cwd().writeFile. Then write a test that checks it returns error.NoSpaceLeft when given std.Io.failing.
Hint: try std.testing.expectError(error.NoSpaceLeft, appendLog(std.Io.failing, "x"));
Show solution
const std = @import("std");
fn appendLog(io: std.Io, line: []const u8) !void { try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = "log.txt", .data = line });}
test "a full disk is an error, not a crash" { try std.testing.expectError(error.NoSpaceLeft, appendLog(std.Io.failing, "x"));}Output:
1/1 main.test.a full disk is an error, not a crash...OKAll 1 tests passed.std.Io.failing pretends the disk is full, so creating log.txt fails with error.NoSpaceLeft. Nothing is written to your real disk.
std.Iois the interface for everything that touches the outside world: files, stdio, network, processes, clocks, sleep, randomness and concurrency.- It works like an allocator: functions take an
io: std.Ioparameter (by value), andmaindecides which implementation is used. init.iofrommain(init: std.process.Init)is astd.Io.Threaded, the default, well-tested implementation.- You can make one yourself with
.init_single_threadedor.init(allocator, .{}), but prefer passinginit.iodown. - In tests, use
std.testing.io, andstd.Io.failingto check error paths. - Under the hood an
Iois justuserdata+vtable, the same shape asstd.mem.Allocator.
Next up: Zig Readers & Writers, the std.Io.Reader and std.Io.Writer interfaces that every stream in Zig is built on.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- I/O as an Interface (0.16.0 release notes): the official explanation, the list of implementations and the upgrade notes.
- Juicy Main (0.16.0 release notes): what
std.process.Initgivesmain, includingio. - Zig 0.17.0 release notes: what changed since 0.16 (the
std.Iodesign stayed the same). - std/Io.zig source (0.17.1): the interface itself; the doc comment at the top lists everything it covers.