Skip to content

Appendix D. Standard Library Map

The Zig standard library is imported as:

The Zig standard library is imported as:

const std = @import("std");

The library is organized as a tree of namespaces. Most programs use only a small part of it.

This appendix lists the major areas and the names most commonly used in ordinary programs.

D.1 Debug and Printing

std.debug

Printing:

std.debug.print("{d}\n", .{123});

Assertions:

std.debug.assert(x > 0);

Panic:

std.debug.panic("bad state", .{});

Useful names:

std.debug.print
std.debug.assert
std.debug.panic

D.2 Memory

std.mem

Byte operations:

std.mem.copyForwards
std.mem.copyBackwards
std.mem.eql
std.mem.indexOf
std.mem.startsWith
std.mem.endsWith

Example:

if (std.mem.eql(u8, a, b)) {
    equal();
}

Splitting:

var it = std.mem.splitScalar(u8, text, ',');

D.3 Heap Allocators

std.heap

Page allocator:

const allocator = std.heap.page_allocator;

General-purpose allocator:

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();

const allocator = gpa.allocator();

Arena allocator:

var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();

Fixed buffer allocator:

var buf: [4096]u8 = undefined;

var fba = std.heap.FixedBufferAllocator.init(&buf);
const allocator = fba.allocator();

D.4 Array Lists

std.ArrayList

Example:

var list = std.ArrayList(u8).init(allocator);
defer list.deinit();

try list.append('A');

Useful fields and functions:

list.items
list.append
list.clearRetainingCapacity
list.deinit

D.5 Hash Maps

std.HashMap
std.AutoHashMap
std.StringHashMap

Example:

var map = std.StringHashMap(i32).init(allocator);
defer map.deinit();

try map.put("one", 1);

Lookup:

if (map.get("one")) |value| {
    use(value);
}

D.6 Formatting

std.fmt

Formatting into memory:

const text = try std.fmt.allocPrint(
    allocator,
    "{d}",
    .{123},
);

Parsing:

const n = try std.fmt.parseInt(i32, "123", 10);

Useful names:

std.fmt.allocPrint
std.fmt.bufPrint
std.fmt.parseInt
std.fmt.parseFloat

D.7 Filesystem

std.fs

Current directory:

const cwd = std.fs.cwd();

Open file:

const file = try cwd.openFile("data.txt", .{});
defer file.close();

Create file:

const file = try cwd.createFile("out.txt", .{});
defer file.close();

Read file:

const data = try file.readToEndAlloc(
    allocator,
    1024 * 1024,
);

Useful names:

std.fs.cwd
std.fs.File
std.fs.Dir

D.8 Input and Output

std.io

Standard output:

const stdout = std.io.getStdOut().writer();
try stdout.print("hello\n", .{});

Buffered writer:

var buf = std.io.bufferedWriter(stdout);
const writer = buf.writer();

Buffered reader:

var buf = std.io.bufferedReader(reader);
const r = buf.reader();

D.9 Process and Environment

std.process
std.posix

Arguments:

var args = std.process.args();

Environment variable:

const home = std.process.getEnvVarOwned(
    allocator,
    "HOME",
);

Exit:

std.process.exit(1);

D.10 Random Numbers

std.rand

Example:

var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();

const x = random.int(u32);

D.11 Time

std.time

Sleep:

std.time.sleep(1_000_000_000);

Timestamp:

const now = std.time.nanoTimestamp();

D.12 JSON

std.json

Parse:

const parsed = try std.json.parseFromSlice(
    T,
    allocator,
    text,
    .{},
);
defer parsed.deinit();

Stringify:

try std.json.stringify(value, .{}, writer);

D.13 Compression

std.compress

Common formats include gzip and zlib.

D.14 Cryptography

std.crypto

Hashing:

std.crypto.hash.sha2

Random bytes:

std.crypto.random

Example:

var bytes: [32]u8 = undefined;
std.crypto.random.bytes(&bytes);

D.15 Networking

std.net

TCP connection:

const stream = try std.net.tcpConnectToHost(
    allocator,
    "example.com",
    80,
);
defer stream.close();

D.16 Testing

std.testing

Equality:

try std.testing.expect(x == y);

Deep equality:

try std.testing.expectEqual(a, b);

String equality:

try std.testing.expectEqualStrings(a, b);

Allocator for tests:

const allocator = std.testing.allocator;

D.17 Math

std.math

Examples:

std.math.max
std.math.min
std.math.clamp
std.math.sqrt
std.math.sin
std.math.cos

D.18 Unicode

std.unicode

UTF-8 validation:

const ok = std.unicode.utf8ValidateSlice(text);

D.19 Build System

std.Build

Example:

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "app",
        .root_source_file = b.path("main.zig"),
    });

    b.installArtifact(exe);
}

D.20 Common Program Skeleton

Most small Zig programs use a pattern like this:

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();

    const allocator = gpa.allocator();

    const stdout = std.io.getStdOut().writer();

    try stdout.print("hello\n", .{});

    _ = allocator;
}

The standard library stays close to the language itself: explicit allocation, explicit errors, explicit cleanup, and direct access to operating system facilities.