Skip to content

Zig Cheatsheet

General-purpose programming language and toolchain for robust, optimal programs.

01

Getting Started

Hello World

Zig uses @import for std lib; print uses comptime format strings.

zig
const std = @import("std");

pub fn main() void {
    std.debug.print("Hello, {s}\n", .{"World"}});
}

Variables

const is immutable, var is mutable. Types are explicit or inferred.

zig
const x: i32 = 10;
var y: i32 = 20;
y += 5;

Functions

Functions use fn keyword; pub makes them public.

zig
fn add(a: i32, b: i32) i32 {
    return a + b;
}

pub fn main() void {
    const std = @import("std");
    std.debug.print("{d}\n", .{add(3, 4)});
}

Build

Zig has a built-in build system and cross-compilation.

zig
# zig build-exe main.zig
# zig run main.zig
02

Types

Integers

Zig has arbitrary bit-width integers: i8, u8, i16, u16, i32, u32, etc.

zig
const a: u8 = 255;
const b: i32 = -100;
const c: usize = 0;

Arrays

[_] infers array length.

zig
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const first = arr[0];
const len = arr.len;

Slices

Slices are views into arrays; .. is exclusive end.

zig
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const slice = arr[1..4]; // [2, 3, 4]

Optionals

?T is optional type; use .? or if-let to unwrap.

zig
var maybe: ?i32 = null;
maybe = 42;
if (maybe) |val| {
    // val is i32 here
}
03

Control Flow

If-Else

If-else are expressions in Zig.

zig
const x: i32 = 5;
if (x > 3) {
    // big
} else {
    // small
}

Switch

Switch must be exhaustive.

zig
const x: u8 = 2;
switch (x) {
    1 => {},
    2 => {},
    else => {},
}

While

The : (i += 1) is the continue expression.

zig
var i: u32 = 0;
while (i < 5) : (i += 1) {
    // loop body
}

For

For iterates over slices/arrays.

zig
const arr = [_]i32{ 1, 2, 3 };
for (arr) |val| {
    // use val
}
04

Memory

Allocators

Zig has no hidden allocations; allocators are explicit.

zig
const std = @import("std");
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    const slice = try allocator.alloc(u8, 100);
    defer allocator.free(slice);
}

Defer

defer runs at scope exit — RAII-like resource cleanup.

zig
const std = @import("std");
pub fn main() void {
    const file = std.fs.cwd().createFile("test.txt", .{}) catch unreachable;
    defer file.close();
}

Was this helpful?