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.debugPrinting:
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.panicD.2 Memory
std.memByte operations:
std.mem.copyForwards
std.mem.copyBackwards
std.mem.eql
std.mem.indexOf
std.mem.startsWith
std.mem.endsWithExample:
if (std.mem.eql(u8, a, b)) {
equal();
}Splitting:
var it = std.mem.splitScalar(u8, text, ',');D.3 Heap Allocators
std.heapPage 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.ArrayListExample:
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.deinitD.5 Hash Maps
std.HashMap
std.AutoHashMap
std.StringHashMapExample:
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.fmtFormatting 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.parseFloatD.7 Filesystem
std.fsCurrent 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.DirD.8 Input and Output
std.ioStandard 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.posixArguments:
var args = std.process.args();Environment variable:
const home = std.process.getEnvVarOwned(
allocator,
"HOME",
);Exit:
std.process.exit(1);D.10 Random Numbers
std.randExample:
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
const x = random.int(u32);D.11 Time
std.timeSleep:
std.time.sleep(1_000_000_000);Timestamp:
const now = std.time.nanoTimestamp();D.12 JSON
std.jsonParse:
const parsed = try std.json.parseFromSlice(
T,
allocator,
text,
.{},
);
defer parsed.deinit();Stringify:
try std.json.stringify(value, .{}, writer);D.13 Compression
std.compressCommon formats include gzip and zlib.
D.14 Cryptography
std.cryptoHashing:
std.crypto.hash.sha2Random bytes:
std.crypto.randomExample:
var bytes: [32]u8 = undefined;
std.crypto.random.bytes(&bytes);D.15 Networking
std.netTCP connection:
const stream = try std.net.tcpConnectToHost(
allocator,
"example.com",
80,
);
defer stream.close();D.16 Testing
std.testingEquality:
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.mathExamples:
std.math.max
std.math.min
std.math.clamp
std.math.sqrt
std.math.sin
std.math.cosD.18 Unicode
std.unicodeUTF-8 validation:
const ok = std.unicode.utf8ValidateSlice(text);D.19 Build System
std.BuildExample:
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.