Zig Cheat Sheet
This page packs the syntax from the whole tutorial onto one screen, so you can look things up quickly. It follows the order of the sidebar. Instead of dozens of loose fragments, each section is one small program you can paste into main.zig and run. Every program here was compiled and run with Zig 0.17.1, and the output under it is what it printed. When you need the “why” behind a line, follow the link to its lesson, or look it up in the language reference for 0.17.1.
Commands
Section titled “Commands”| Task | Command |
|---|---|
| Check the version | zig version |
| Run a file | zig run main.zig (arguments after --: zig run main.zig -- a b) |
| Build an executable | zig build-exe main.zig |
| Pick a build mode | -O debug (default), -O safe, -O fast, -O small |
| Cross-compile | zig build-exe main.zig -target x86_64-windows |
| Run tests in a file | zig test main.zig |
| New project | zig init (or zig init -m for a minimal one) |
| Build / run / test a project | zig build, zig build run, zig build test |
| Pass a build option | zig build -Doptimize=fast -Dtarget=aarch64-linux |
| Add a dependency | zig fetch --save <url> |
| Format code | zig fmt . (zig fmt --check . in CI) |
Docs from /// comments |
zig build-lib -femit-docs -fno-emit-bin main.zig |
| Standard library docs | zig std |
Where Zig and std live |
zig env |
| Compile C | zig cc hello.c -o hello |
More in Zig Get Started, Zig Tools & Setup and Zig Build System.
Basics
Section titled “Basics”Variables, numbers, casting, strings and format specifiers:
const std = @import("std");
const max_users = 100; // top-level constant
pub fn main() void { // Variables: const by default, var if it changes const name = "Ada"; // *const [3:0]u8, coerces to []const u8 var count: u32 = 10; // var needs a fixed-size type count += 1; const ratio: f64 = 0.75; const ok = true; var later: i32 = undefined; // set before you read it later = -5; std.debug.print("{s} {d} {d} {} {d} {d}\n", .{ name, count, ratio, ok, later, max_users });
// Integer math: signed / needs @divTrunc or @divFloor const a: i32 = -7; const b: i32 = 2; std.debug.print("{d} {d} {d}\n", .{ @divTrunc(a, b), @divFloor(a, b), @rem(a, b) });
// Overflow on purpose: wrapping +%, saturating +| const x: u8 = 250; std.debug.print("{d} {d}\n", .{ x +% 10, x +| 10 });
// Casting const big: u32 = 300; const small: u8 = @truncate(big); // keep the low bits const fits: u8 = @intCast(count); // checked in debug builds const f: f64 = @floatFromInt(count); const back: i32 = @round(2.6); // float to int with rounding std.debug.print("{d} {d} {d} {d}\n", .{ small, fits, f, back });
// Strings are byte slices const s: []const u8 = "Hello, Zig"; std.debug.print("{d} {c} {s} {}\n", .{ s.len, s[0], s[7..], std.mem.eql(u8, s[0..5], "Hello") });
// Format specifiers std.debug.print("[{d:>5}] [{s:<5}] [{x}] [{b}] [{d:.2}] [{any}]\n", .{ 42, "ab", 255, 5, 3.14159, [_]u8{ 1, 2 } });}Output:
Ada 11 0.75 true -5 100-3 -4 -14 25544 11 11 310 H Zig true[ 42] [ab ] [ff] [101] [3.14] [{ 1, 2 }]constunless it changes; Zig rejects avarthat never changes, and any unused local.- A plain number like
5is acomptime_int, sovarneeds a type:var count: u32 = 10;. {d}numbers,{s}strings,{c}a byte as a character,{x}hex,{b}binary,{any}anything,{t}enum and error names,{?d}optionals.{}works forbool.
See Zig Variables, Zig Integers, Zig Type Casting, Zig Strings and Zig Format Strings.
Control flow
Section titled “Control flow”if, switch, loops, labels, blocks and defer:
const std = @import("std");
pub fn main() void { defer std.debug.print("defer runs last\n", .{});
// if is an expression (needs else) const temp: i32 = 23; const feel: []const u8 = if (temp > 20) "warm" else "cold";
// switch: must cover every value const grade: u8 = 85; const letter: u8 = switch (grade) { 90...100 => 'A', 80...89 => 'B', 0...79 => 'C', else => '?', }; std.debug.print("{s} {c}\n", .{ feel, letter });
// while with a continue expression var i: u32 = 0; while (i < 3) : (i += 1) std.debug.print("w{d} ", .{i});
// for over a range, and over a slice with its index for (0..3) |n| std.debug.print("r{d} ", .{n}); const items = [_][]const u8{ "a", "b" }; for (items, 0..) |item, idx| std.debug.print("[{d}]{s}", .{ idx, item }); std.debug.print("\n", .{});
// labeled loop: break out of both outer: for (0..3) |row| { for (0..3) |col| { if (row * col == 2) { std.debug.print("found {d},{d}\n", .{ row, col }); break :outer; } } }
// labeled block returns a value const sum = blk: { var total: u32 = 0; for (1..5) |n| total += @intCast(n); break :blk total; }; std.debug.print("sum {d}\n", .{sum});}Output:
warm Bw0 w1 w2 r0 r1 r2 [0]a[1]bfound 1,2sum 10defer runs lastswitchmust cover every value: useelseor list them all.90...100is an inclusive range.0..3is 0, 1, 2 (the end is not included).for (items, 0..) |item, i|adds an index.- A
deferruns when its block ends, last one first.
See Zig If…Else, Zig Switch, Zig While, Zig For, Zig Break/Continue, Zig Blocks and Zig Defer.
Functions, arrays, slices and pointers
Section titled “Functions, arrays, slices and pointers”const std = @import("std");
// Functions: parameters are const; pass a pointer to change somethingfn double(x: i32) i32 { return x * 2;}
fn addOne(n: *i32) void { n.* += 1;}
fn sum(values: []const i32) i32 { var total: i32 = 0; for (values) |v| total += v; return total;}
pub fn main() void { var n: i32 = 5; addOne(&n); std.debug.print("{d} {d}\n", .{ double(n), n });
// Arrays: fixed size, known at compile time var nums = [_]i32{ 4, 8, 15, 16, 23 }; const zeros: [3]u8 = @splat(0); const grid = [2][3]u8{ .{ 1, 2, 3 }, .{ 4, 5, 6 } }; nums[0] = 1; std.debug.print("{d} {any} {d}\n", .{ nums.len, zeros, grid[1][2] });
// Slices: pointer + length, bounds checked const middle = nums[1..4]; const tail = nums[2..]; std.debug.print("{any} {any} {d}\n", .{ middle, tail, sum(&nums) });
// Join comptime-known strings and arrays with ++ const hello = "Hel" ++ "lo"; std.debug.print("{s}\n", .{hello});
// Pointers const p: *i32 = &nums[1]; p.* = 99; const ro: *const i32 = &nums[1]; // read-only view std.debug.print("{d} {d}\n", .{ nums[1], ro.* });}Output:
12 65 { 0, 0, 0 } 6{ 8, 15, 16 } { 15, 16, 23 } 63Hello99 99- Parameters are read-only. To change the caller’s variable, take a pointer (
*i32) and write through it with.*. [_]i32{ ... }lets the compiler count;@splat(0)fills an array with one value.nums[1..4]is a slice of items 1, 2 and 3.&numsturns an array into a slice argument.++only joins values known at compile time. At run time, useallocator.printor anArrayList.
See Zig Functions, Zig Arrays, Zig Slices and Zig Pointers.
Structs, enums, unions, optionals and errors
Section titled “Structs, enums, unions, optionals and errors”const std = @import("std");
const Point = struct { x: i32 = 0, // default value y: i32 = 0,
fn moved(self: Point, dx: i32) Point { return .{ .x = self.x + dx, .y = self.y }; }};
const Color = enum { red, green, blue };
const Shape = union(enum) { circle: f64, square: f64,};
const ParseError = error{ Empty, TooLong };
fn check(text: []const u8) ParseError!usize { if (text.len == 0) return error.Empty; if (text.len > 5) return error.TooLong; return text.len;}
fn firstEven(xs: []const u32) ?u32 { for (xs) |x| if (x % 2 == 0) return x; return null;}
pub fn main() !void { // Structs and methods const p: Point = .{ .x = 1 }; const q = p.moved(4); std.debug.print("{d},{d} {any}\n", .{ q.x, q.y, p });
// Enums const c: Color = .green; std.debug.print("{t} {s} {d}\n", .{ c, @tagName(Color.blue), @backingInt(c) });
// Tagged unions with switch and captures const s: Shape = .{ .square = 3 }; const area = switch (s) { .circle => |r| std.math.pi * r * r, .square => |side| side * side, }; std.debug.print("{t} {d}\n", .{ s, area });
// Tuples and anonymous structs const pair = .{ 1, "one" }; std.debug.print("{d} {s}\n", .{ pair[0], pair[1] });
// Optionals: orelse, if capture, .? const evens = [_]u32{ 3, 5, 8 }; const none = [_]u32{ 1, 3 }; const e = firstEven(&evens) orelse 0; if (firstEven(&none)) |v| std.debug.print("got {d}\n", .{v}) else std.debug.print("none\n", .{}); std.debug.print("{d} {d}\n", .{ e, firstEven(&evens).? });
// Errors: try, catch, catch |err|, if with error capture const len = try check("zig"); const fallback = check("") catch 0; const name = check("toolong") catch |err| switch (err) { error.Empty => 0, error.TooLong => 5, }; if (check("")) |v| { std.debug.print("ok {d}\n", .{v}); } else |err| { std.debug.print("failed: {t}\n", .{err}); } std.debug.print("{d} {d} {d}\n", .{ len, fallback, name });}Output:
5,0 .{ .x = 1, .y = 0 }green blue 1square 91 onenone8 8failed: Empty3 0 5.{ .x = 1 }builds a struct when the type is known from the left side.@backingInt(c)gives an enum’s number (it replaced@intFromEnumin 0.17).- Optionals:
x orelse default,if (x) |v|, andx.?(panics in debug builds if it’snull). - Errors:
trypasses the error up,catchhandles it, andif (...) |v| {} else |err| {}does both. A function that usestryneeds!in its return type.
See Zig Structs, Zig Enums, Zig Tagged Unions, Zig Optionals, Zig Errors and Zig Try & Catch.
Memory and collections
Section titled “Memory and collections”main can take init: std.process.Init, which hands you allocators and I/O:
const std = @import("std");
const Item = struct { name: []const u8, price: u32 };
fn cheaper(_: void, a: Item, b: Item) bool { return a.price < b.price;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; // leak-checking in debug builds const arena = init.arena.allocator(); // freed when main returns
// alloc/free and create/destroy const buf = try gpa.alloc(u8, 4); defer gpa.free(buf); @memset(buf, 'z'); const num = try gpa.create(i32); defer gpa.destroy(num); num.* = 7;
// Formatting into new memory const msg = try gpa.print("{s} {d}", .{ buf, num.* }); defer gpa.free(msg); std.debug.print("{s}\n", .{msg});
// ArrayList: starts .empty, pass the allocator to each call var list: std.ArrayList(Item) = .empty; defer list.deinit(gpa); try list.append(gpa, .{ .name = "tea", .price = 3 }); try list.append(gpa, .{ .name = "cake", .price = 5 }); try list.append(gpa, .{ .name = "bun", .price = 2 });
// Sorting (stable) std.mem.sort(Item, list.items, {}, cheaper); for (list.items) |it| std.debug.print("[{s} {d}]", .{ it.name, it.price }); std.debug.print("\n", .{});
// Hash map var stock: std.StringHashMapUnmanaged(u32) = .empty; defer stock.deinit(gpa); try stock.put(gpa, "tea", 10); try stock.put(gpa, "bun", 0); if (stock.get("tea")) |n| std.debug.print("tea: {d}\n", .{n}); std.debug.print("{} {d}\n", .{ stock.contains("cake"), stock.count() });
// Arena: no frees needed const words = try arena.alloc([]const u8, 2); words[0] = "no"; words[1] = "free"; std.debug.print("{s} {s}\n", .{ words[0], words[1] });}Output:
zzzz 7[bun 2][tea 3][cake 5]tea: 10false 2no free- Put
defer free(ordefer deinit) right under every allocation. ArrayListand the unmanaged hash maps start as.emptyand take the allocator in every call that allocates.std.mem.sort(T, items, context, lessThan)is stable.lessThanmust use<, not<=.- In a function that allocates more than once,
errdefer gpa.free(x);cleans up if a later step fails.
See Zig Allocators, Zig Arena Allocator, Zig Errdefer, Zig ArrayList, Zig HashMap and Zig Sorting & Searching.
Comptime and generics
Section titled “Comptime and generics”const std = @import("std");
// Generic function: comptime type parameterfn biggest(comptime T: type, xs: []const T) T { var best = xs[0]; for (xs) |x| best = @max(best, x); return best;}
// Generic type: a function that returns a structfn Box(comptime T: type) type { return struct { value: T, const Self = @This(); fn get(self: Self) T { return self.value; } };}
// anytype: the type is inferred from the argumentfn describe(x: anytype) void { std.debug.print("{s}\n", .{@typeName(@TypeOf(x))});}
const Config = struct { port: u16, debug: bool };
pub fn main() void { std.debug.print("{d} {d}\n", .{ biggest(u8, &.{ 3, 9, 4 }), biggest(f32, &.{ 1.5, 0.5 }) });
const b: Box(i32) = .{ .value = 42 }; std.debug.print("{d}\n", .{b.get()}); describe(b);
// comptime block: runs while compiling const squares = comptime blk: { var t: [5]u32 = undefined; for (&t, 0..) |*v, i| v.* = @intCast(i * i); break :blk t; }; std.debug.print("{any}\n", .{squares});
// Reflection: walk struct fields (0.17 style) const info = @typeInfo(Config).@"struct"; inline for (info.field_names, info.field_types) |name, T| { std.debug.print("{s}: {s}\n", .{ name, @typeName(T) }); }
// Vectors (SIMD) const v: @Vector(4, f32) = .{ 1, 2, 3, 4 }; const w = v * @as(@Vector(4, f32), @splat(10)); std.debug.print("{any} {d}\n", .{ w, @reduce(.Add, w) });}Output:
9 1.542main.Box(i32){ 0, 1, 4, 9, 16 }port: u16debug: bool{ 10, 20, 30, 40 } 100comptime T: typemakes a generic function; a function that returnstypemakes a generic struct.@typeInfo(T).@"struct"hasfield_namesandfield_typesin 0.17. Loop over them withinline for.@Vector(4, f32)does math on all four numbers at once.
See Zig Comptime, Zig Generic Functions, Zig Generic Data Structures, Zig Reflection and Zig Vectors.
I/O, files and arguments
Section titled “I/O, files and arguments”Since 0.16, I/O goes through init.io:
const std = @import("std");
fn square(n: u64) u64 { return n * n;}
pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa;
// Buffered stdout: print, then flush var buf: [512]u8 = undefined; var stdout = std.Io.File.stdout().writer(io, &buf); const out = &stdout.interface;
// Command-line arguments (args[0] is the program) const args = try init.minimal.args.toSlice(init.arena.allocator()); try out.print("{d} arg(s)\n", .{args.len});
// Write a file, read it back const cwd = std.Io.Dir.cwd(); try cwd.writeFile(io, .{ .sub_path = "note.txt", .data = "one\ntwo\n" }); const data = try cwd.readFileAlloc(io, "note.txt", gpa, .limited(1024)); defer gpa.free(data); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, data, "\n"), '\n'); while (lines.next()) |line| try out.print("line: {s}\n", .{line});
// Run a function through io.async and wait for it var future = io.async(square, .{12}); try out.print("{d}\n", .{future.await(io)});
try out.flush(); // without this, nothing is printed}Output:
1 arg(s)line: oneline: two144std.debug.printgoes to stderr and needs notry. For real output, write to stdout through a buffered writer and flush.- Take
&stdout.interfaceas a pointer; copying the interface breaks it. - File functions live on
std.Io.Dirandstd.Io.Fileand takeio. Closing a file isfile.close(io). io.async(f, .{args})gives a future; alwaysawait(orcancel) it.
See Zig Main & Init, Zig Output, Zig Readers & Writers, Zig File I/O, Zig Command-Line Arguments and Zig Async & Futures.
Testing
Section titled “Testing”Run with zig test main.zig:
const std = @import("std");
fn add(a: i32, b: i32) i32 { return a + b;}
fn fail() !void { return error.Oops;}
test "add" { try std.testing.expect(add(2, 2) == 4); try std.testing.expectEqual(5, add(2, 3));}
test "errors, strings and leaks" { const a = std.testing.allocator; // fails the test on a leak const p = try a.alloc(u8, 8); defer a.free(p); try std.testing.expectEqualStrings("hi", "hi"); try std.testing.expectError(error.Oops, fail());}Output:
1/2 main.test.add...OK2/2 main.test.errors, strings and leaks...OKAll 2 tests passed.test blocks are compiled only by zig test (or zig build test), never into your program. See Zig Testing and Zig Testing Allocator.
Build system
Section titled “Build system”A small build.zig with run and test steps, tested with zig build run -- x y and zig build test on 0.17.1:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const mod = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, });
const exe = b.addExecutable(.{ .name = "app", .root_module = mod }); b.installArtifact(exe);
const run = b.addRunArtifact(exe); run.addPassthruArgs(); b.step("run", "Run the app").dependOn(&run.step);
const tests = b.addTest(.{ .root_module = mod }); b.step("test", "Run the tests").dependOn(&b.addRunArtifact(tests).step);}zig init writes a longer version of this with comments. See Zig Build System and Zig Packages & Dependencies.
Calling C
Section titled “Calling C”Declare a C function with extern and link libc with -lc (zig run main.zig -lc prints 42):
const std = @import("std");
extern "c" fn abs(x: c_int) c_int;
pub fn main() void { std.debug.print("{d}\n", .{abs(-42)});}For whole C headers, use the translate-c package from build.zig; @cImport was removed in 0.17. See Zig and C and Zig Calling C Libraries.
Old code? Quick translations
Section titled “Old code? Quick translations”If an example from the web doesn’t compile, it’s probably from an older Zig. The 0.17.0 release notes list what changed in the latest release, and these are the changes you’ll hit most:
| Old | 0.17.1 |
|---|---|
std.io.getStdOut().writer() |
std.Io.File.stdout().writer(io, &buf) + flush() |
std.heap.GeneralPurposeAllocator |
init.gpa (or std.heap.SafeAllocator) |
std.ArrayList(T).init(a) |
var list: std.ArrayList(T) = .empty; |
std.fs.cwd() |
std.Io.Dir.cwd() |
[_]u8{0} ** 4 |
@splat(0) |
ReleaseFast |
fast |
@intFromEnum |
@backingInt |
The full list, with how we checked each row, is in Zig Upgrading.
- New names are
constunless they change, and nothing may go unused. - Strings are
[]const u8; compare them withstd.mem.eql. - Errors are values:
!T,try,catch; “maybe nothing” is?Twithorelse. - Allocation is explicit: get
init.gpafrommain, and putdefer freeright after each allocation. - Containers start as
.emptyand take the allocator in each call; stdout needs aflush.
Next up: Zig Keywords, every keyword in the language with a one-line meaning.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference (0.17.1): the exact rules behind every line on this page.
- Zig standard library docs (0.17.1): every type and function that ships with Zig.
- Zig build system guide: the official walk-through of
build.zig. - Zig 0.17.0 release notes: what changed in the version this page was tested on.