Zig Main & Init
Every Zig program starts in main. You’ve written it two ways in this tutorial: the short pub fn main() void, and pub fn main(init: std.process.Init) !void, which hands you useful things like init.gpa. This page explains the second one properly. Since Zig 0.16, main can ask for an init value that holds everything a program usually sets up first: an I/O interface, two allocators, the command-line arguments and the environment variables. Knowing what’s in it, and when to use the simpler forms, makes every program after this one easier to write.
Everything here was checked with Zig 0.17.1.
The shapes main can take
Section titled “The shapes main can take”main must be pub (the standard library’s startup code calls it from another file, see Zig Modules & Imports). Its parameter can be one of three things:
| Parameter | What you get |
|---|---|
none: main() |
Nothing. No arguments, no environment, no I/O handed to you. |
init: std.process.Init.Minimal |
The raw arguments and environment, nothing else. |
init: std.process.Init |
Arguments and environment, plus ready-made I/O and allocators. |
And its return type can be void, !void, u8 or !u8 (or noreturn, for a main that never returns). Anything else is a compile error:
error: expected return type of main to be 'void', '!void', 'noreturn', 'u8', or '!u8'The return type decides the exit code, the number your program hands back to the shell or script that started it. 0 means success, anything else means something went wrong.
Returning an error from main
Section titled “Returning an error from main”With !void, main can use try. If an error comes out of main, Zig prints it and exits with code 1:
const std = @import("std");
pub fn main() !void { std.debug.print("checking the config...\n", .{}); return error.ConfigMissing;}Run it and print the exit code ($? in bash and zsh):
zig build-exe main.zig./mainecho "exit code: $?"You’ll see:
checking the config...error: ConfigMissingmain.zig:5:5: 0x11e3141 in main (main.zig) return error.ConfigMissing; ^exit code: 1In debug builds you also get an error return trace showing where the error came from (Zig Error Return Traces explains them). In the release modes it’s just error: ConfigMissing. That makes !void the most practical return type for real programs: you can try everything, and failures still end with a readable message and a non-zero exit code.
Choosing the exit code with u8
Section titled “Choosing the exit code with u8”Return a u8 when you want a specific exit code:
const std = @import("std");
pub fn main() u8 { std.debug.print("nothing to do\n", .{}); return 3;}You’ll see:
nothing to doexit code: 3Scripts and tools like make look at that number, so command-line programs often use different codes for different problems. Zig Command-Line Arguments shows the common conventions and std.process.exit.
A tour of std.process.Init
Section titled “A tour of std.process.Init”Here’s one program that uses each part of init:
const std = @import("std");
pub fn main(init: std.process.Init) !void { // io: the door to the outside world (files, stdout, time, network) var buf: [256]u8 = undefined; var stdout = std.Io.File.stdout().writer(init.io, &buf); const out = &stdout.interface;
// arena: memory that lives until the program ends const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); try out.print("arguments after the program name: {d}\n", .{args.len - 1});
// gpa: memory you free yourself const squares = try init.gpa.alloc(u32, 4); defer init.gpa.free(squares); for (squares, 0..) |*s, i| s.* = @intCast(i * i); try out.print("squares: {any}\n", .{squares});
// environ_map: environment variables const color = init.environ_map.get("MYAPP_COLOR") orelse "blue"; try out.print("color: {s}\n", .{color});
try out.flush();}Output:
arguments after the program name: 0squares: { 0, 1, 4, 9 }color: blueRun it as MYAPP_COLOR=red zig run main.zig -- a b and you get 2 arguments and color: red. Here’s what each field is.
init.io
Section titled “init.io”init.io is a value of type std.Io: the interface for everything that talks to the world outside your program. Writing to stdout, reading files, sleeping, getting the time, networking and running things at the same time all go through it.
Why pass it around instead of just calling the operating system? For the same reason Zig passes allocators around: the code that uses I/O doesn’t decide how it’s done. Today init.io is a thread-based implementation that fits your target. A test can hand your code std.testing.io instead, and other implementations can be swapped in later without changing your functions. The Juicy Main section of the 0.16.0 release notes introduced it, and Zig I/O Interface goes deeper.
In practice: anything that does I/O takes an io: std.Io parameter, and you pass init.io down from main. The buffered stdout writer above is the pattern from Zig Output, and the flush at the end matters: without it, nothing in the buffer gets printed.
init.gpa
Section titled “init.gpa”init.gpa is a general-purpose allocator (std.mem.Allocator) for memory you allocate and free yourself, like the squares above. Which allocator it is depends on the build mode:
- In
debugandsafebuilds it’sstd.heap.SafeAllocator, which checks your work: it reports leaks when the program ends and catches double frees. - In
fastandsmallbuilds it’s a faster allocator without those checks (std.heap.smp_allocator, orstd.heap.c_allocatorif you link libc).
So you get leak checking while you develop and speed when you ship, without changing a line. A leak report doesn’t change the exit code, though, so read your program’s output. Zig Allocators and Zig Memory Leaks cover allocators in depth.
init.arena
Section titled “init.arena”init.arena is an arena: you allocate from it and never free anything individually, because the whole arena is freed when the program ends. It’s the right home for things that live as long as the program does, like the argument list or a config file you read at startup. See Zig Arena Allocator for how arenas work.
One detail trips everyone up once: init.arena is a *std.heap.ArenaAllocator, not an allocator. Call .allocator() on it. Pass it directly and you get:
main.zig:4:52: error: expected type 'mem.Allocator', found '*heap.ArenaAllocator' const args = try init.minimal.args.toSlice(init.arena); ~~~~^~~~~~init.minimal.args
Section titled “init.minimal.args”The command-line arguments. toSlice gives you all of them as a slice of strings, with args[0] being the program itself. It needs an allocator because on Windows the arguments have to be decoded first, and the arena is the natural choice since the list lives until the end. Zig Command-Line Arguments is all about them.
init.environ_map
Section titled “init.environ_map”The environment variables, as a map from name to value. get returns an optional, so orelse supplies a default. Variables are only available through main in Zig 0.16 and later: there’s no global getenv you can call from anywhere. Zig Environment Variables shows the patterns.
init has one more field, init.preopens, for files and folders the parent process hands over at startup. It’s mostly used by WebAssembly (WASI) programs; you can ignore it elsewhere.
Passing init’s pieces down
Section titled “Passing init’s pieces down”init itself belongs in main. Other functions shouldn’t take the whole init; they take just the pieces they need, as plain parameters. That keeps them easy to test and clear about what they touch:
const std = @import("std");
const Item = struct { name: []const u8, price_cents: u32 };
/// Builds the report text in memory, then writes it to stdout.fn printReport(io: std.Io, gpa: std.mem.Allocator, items: []const Item) !void { var total: u32 = 0; for (items) |item| total += item.price_cents;
const text = try gpa.print("{d} items, total {d}.{d:0>2}\n", .{ items.len, total / 100, total % 100 }); defer gpa.free(text);
try std.Io.File.stdout().writeStreamingAll(io, text);}
pub fn main(init: std.process.Init) !void { const items = [_]Item{ .{ .name = "coffee", .price_cents = 350 }, .{ .name = "bagel", .price_cents = 225 }, }; try printReport(init.io, init.gpa, &items);}Output:
2 items, total 5.75Read printReport’s signature and you know what it does without reading the body: it does I/O, it allocates, and it reads a list of items. That’s the Zig habit: dependencies are parameters. {d:0>2} pads the cents to two digits, so 5 cents prints as 05 (Zig Format Strings has all the options).
Init.Minimal: just the raw parts
Section titled “Init.Minimal: just the raw parts”If you’d rather set things up yourself, take std.process.Init.Minimal. It has only two fields, args and environ, and Zig doesn’t create any allocator or I/O for you:
const std = @import("std");
pub fn main(init: std.process.Init.Minimal) !void { // No ready-made allocators here: make the one you want. var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator();
const args = try init.args.toSlice(arena); std.debug.print("{d} argument(s)\n", .{args.len});
const shell = init.environ.getAlloc(arena, "MYAPP_SHELL") catch "not set"; std.debug.print("shell: {s}\n", .{shell});}Output:
1 argument(s)shell: not setNotice init.args instead of init.minimal.args: with Minimal, the struct you get is the minimal part. getAlloc copies one variable’s value and returns an error if it’s missing, hence the catch.
When is this worth it? When you need a specific allocator or I/O setup for the whole program, or you’re writing something very small or low-level and don’t want the standard setup. For everyday programs, std.process.Init is less code and does the right thing.
The plain forms: when they’re fine
Section titled “The plain forms: when they’re fine”pub fn main() void and pub fn main() !void are still completely valid, and they’re the right choice when you don’t need what init offers:
- Learning and small examples.
std.debug.printneeds no I/O value and can’t fail, which is why most examples in this tutorial usepub fn main() void. - Programs with no arguments, no environment and no heap memory. A calculation that prints its result doesn’t need
init.
The moment you need arguments, environment variables, stdout, files or an allocator, switch to init. You could make your own I/O and allocator in a plain main, and older code does exactly that:
const std = @import("std");
pub fn main() !void { // No Init, so make our own I/O and allocator. var threaded: std.Io.Threaded = .init_single_threaded; const io = threaded.io();
var safe: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{}); defer _ = safe.deinit(); const gpa = safe.allocator();
const msg = try gpa.print("{d} + {d} = {d}\n", .{ 2, 3, 2 + 3 }); defer gpa.free(msg); try std.Io.File.stdout().writeStreamingAll(io, msg);}Output:
2 + 3 = 5It works, but it’s six lines of setup that init gives you for free, with fewer choices to get wrong. And there’s no way to get the arguments or environment here at all: in Zig 0.16 and later they only reach main through its parameter.
One error you’ll meet
Section titled “One error you’ll meet”If you add the init parameter but don’t use it yet, Zig complains, like it does for any unused parameter:
const std = @import("std");
pub fn main(init: std.process.Init) void { std.debug.print("hi\n", .{});}main.zig:3:13: error: unused function parameterpub fn main(init: std.process.Init) void { ^~~~Either drop the parameter (pub fn main() void) or write _ = init; until you use it.
Practice
Section titled “Practice”1. Exit code from an argument count
Section titled “1. Exit code from an argument count”Write a main that returns exit code 0 when the program gets exactly one argument (after the program name) and 2 otherwise, printing usage: greet NAME in that case.
Hint: return !u8. Get the arguments with init.minimal.args.toSlice(init.arena.allocator()) and check args.len.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !u8 { const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len != 2) { std.debug.print("usage: greet NAME\n", .{}); return 2; } std.debug.print("Hello, {s}!\n", .{args[1]}); return 0;}Output:
usage: greet NAMEzig run passes no arguments, so args.len is 1 and the exit code is 2. With zig run main.zig -- Ada it prints Hello, Ada! and exits with 0. !u8 lets you use try and still choose the exit code.
2. Pass the pieces down
Section titled “2. Pass the pieces down”Write fn shout(gpa: std.mem.Allocator, text: []const u8) ![]u8 that returns an upper-case copy of text (use std.ascii.upperString), and call it from a main that takes init. Free the result.
Hint: allocate with try gpa.alloc(u8, text.len), then std.ascii.upperString(buffer, text). In main, pass init.gpa and defer init.gpa.free(...).
Show solution
const std = @import("std");
fn shout(gpa: std.mem.Allocator, text: []const u8) ![]u8 { const loud = try gpa.alloc(u8, text.len); _ = std.ascii.upperString(loud, text); return loud;}
pub fn main(init: std.process.Init) !void { const loud = try shout(init.gpa, "zig is fun"); defer init.gpa.free(loud); std.debug.print("{s}\n", .{loud});}Output:
ZIG IS FUNshout doesn’t know or care where its memory comes from: in a test you’d pass std.testing.allocator, in main you pass init.gpa. Remove the defer line and the debug build reports the leak when the program ends.
3. Fix the arena mistake
Section titled “3. Fix the arena mistake”This doesn’t compile. Fix it.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena); std.debug.print("{d} argument(s)\n", .{args.len});}Hint: read the error: it wants a mem.Allocator, and you’re passing an ArenaAllocator pointer.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); std.debug.print("{d} argument(s)\n", .{args.len});}Output:
1 argument(s)init.arena is the arena itself; .allocator() gives you the std.mem.Allocator interface that functions expect. The same is true for every allocator type: you pass .allocator(), not the struct.
maincan take no parameter,std.process.Init.Minimal(raw args and environment) orstd.process.Init(everything set up).- It returns
void,!void,u8or!u8. An error frommainprintserror: Nameand exits with code 1; au8is the exit code. init.iois thestd.Iointerface: pass it to anything that does I/O, and flush buffered writers.init.gpachecks for leaks indebug/safeand is fast infast/small.init.arenais freed at exit: call.allocator()on it.- Arguments are
init.minimal.args, the environment isinit.environ_map, and onlymainreceives them. - Pass
ioandgpato other functions as parameters instead of passinginitaround. pub fn main() voidis fine for small programs that need none of this.
Next up: Zig Command-Line Arguments, reading what the user typed, turning text into numbers and handling mistakes.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig 0.16.0 release notes: Juicy Main: where
std.process.Initwas introduced, with the reasons behind it. - Zig language reference: Entry Point: the official rules for
mainand its return types. - Zig 0.17.0 release notes: SafeAllocator Introduced: the allocator behind
init.gpain debug and safe builds. - Zig 0.17.1 standard library docs: look up
std.process.Init,std.Ioandstd.process.Args.