Zig | Sheetly Cheat Sheet

Last Updated: November 21, 2025

Zig

Modern systems programming language

Basic Syntax

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    try stdout.print("Hello, {s}!\n", .{"World"});
}

// Function with error handling
fn divide(a: f32, b: f32) !f32 {
    if (b == 0) return error.DivisionByZero;
    return a / b;
}

// Compile-time execution
fn fibonacci(n: u32) u32 {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

const fib10 = comptime fibonacci(10);

Memory Management

Item Description
Allocator Explicit memory management
defer Execute at scope end
errdefer Execute on error
No hidden control flow Explicit is better
No hidden allocations All allocations visible
Compile-time execution comptime keyword

Error Handling

const FileError = error{
    AccessDenied,
    FileNotFound,
};

fn openFile(path: []const u8) FileError!File {
    // Implementation
}

// Using catch
const file = openFile("test.txt") catch |err| {
    std.debug.print("Error: {}\n", .{err});
    return err;
};

// Using try
const file2 = try openFile("test.txt");

Best Practices

  • Use defer for cleanup (like Go)
  • Leverage compile-time execution
  • Explicit error handling with try/catch
  • No hidden control flow or allocations

💡 Pro Tips

Quick Reference

Zig aims to replace C with better safety

← Back to Data Science & ML | Browse all categories | View all cheat sheets