Zig Cheat Sheet
Core Zig syntax covering variables, error unions, control flow, structs, and compile-time features for systems programming.
2 PagesAdvancedMar 22, 2026
Basics
Variables and formatted printing.
zig
const std = @import("std");pub fn main() void { std.debug.print("Hello, {s}!\n", .{"World"}); const x: i32 = 42; // const = immutable var y: i32 = 10; // var = mutable y += 1; std.debug.print("x={d}, y={d}\n", .{ x, y });}
Error Handling
Error unions, catch, and try.
zig
const std = @import("std");const MyError = error{ NotFound, OutOfRange };fn getItem(index: usize) MyError!i32 { if (index > 10) return MyError.OutOfRange; return 42;}pub fn main() void { const value = getItem(3) catch |err| { std.debug.print("error: {}\n", .{err}); return; }; std.debug.print("value: {d}\n", .{value}); // try propagates the error to the caller: // const v = try getItem(3);}
Control Flow
Branching, looping, and scope-exit cleanup.
- if (cond) { } else { }- Standard conditional expression/statement
- while (cond) { }- Loop while a condition holds
- for (items) |item| { }- Iterate over a slice or array
- switch (x) { 1 => ..., else => ... }- Pattern-based branching
- defer cleanup();- Runs cleanup when the current scope exits
- orelse- Provides a default when unwrapping an optional (?T)
Structs & Types
Custom types and Zig-specific type constructs.
- const Point = struct { x: f32, y: f32 };- Defines a struct type
- ?T- Optional type, either a T value or null
- !T- Error union, either an error or a T value
- []const u8- String slice (byte slice), Zig's idiomatic string type
- comptime- Marks a value or code evaluated at compile time
- std.ArrayList(T)- Growable dynamic array from the standard library
Pro Tip
Use defer right after acquiring a resource (allocation, file open) so cleanup code lives next to the acquisition — it always runs, even on early returns or errors.
Was this cheat sheet helpful?
Explore Topics
#Zig#ZigCheatSheet#Programming#Advanced#ErrorHandling#ControlFlow#StructsTypes#Syntax#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance