Skip to content

Zig Other Collections

Most Zig programs get by with two collections: an ArrayList and a hash map. But a few jobs come up often enough that the standard library has a tool made for them: always grabbing the most urgent task, adding and removing at both ends of a queue, tracking yes/no flags for thousands of things, or linking items together without moving them. This lesson is a tour of those tools, with one small example each and an honest word on when you’d actually use them.

All of them follow the rules you already know: start from .empty (or an init function), pass the allocator to calls that may allocate, and deinit when you’re done.

Priority queue: always take the most important item

Section titled “Priority queue: always take the most important item”

A priority queue lets you add items in any order and always take out the “best” one next: the most urgent task, the shortest distance, the earliest timer. You tell it what “best” means with a compare function:

const std = @import("std");
const Task = struct {
name: []const u8,
priority: u8, // 1 is most urgent
};
fn mostUrgentFirst(_: void, a: Task, b: Task) std.math.Order {
return std.math.order(a.priority, b.priority);
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var tasks: std.PriorityQueue(Task, void, mostUrgentFirst) = .empty;
defer tasks.deinit(gpa);
try tasks.push(gpa, .{ .name = "write docs", .priority = 3 });
try tasks.push(gpa, .{ .name = "fix crash", .priority = 1 });
try tasks.push(gpa, .{ .name = "lunch", .priority = 2 });
try tasks.push(gpa, .{ .name = "reply to Bo", .priority = 2 });
std.debug.print("next up: {s}\n", .{tasks.peek().?.name});
while (tasks.pop()) |task| {
std.debug.print("{d} {s}\n", .{ task.priority, task.name });
}
}

Output:

next up: fix crash
1 fix crash
2 reply to Bo
2 lunch
3 write docs
  • std.PriorityQueue(Task, void, mostUrgentFirst) takes the item type, a context type (void, we don’t need one) and the compare function.
  • The compare function returns a std.math.Order. Returning .lt means “a should come out before b”, so std.math.order(a.priority, b.priority) makes the smallest number come out first. For largest first, flip it: std.math.order(a, b).invert().
  • push adds, pop removes the best item (or returns null when empty), peek looks at it without removing.

Look at the two tasks with priority 2: “reply to Bo” came out before “lunch”, even though “lunch” was added first. A priority queue only promises the best item comes out next. Among equals, the order is not guaranteed. If you need first-come-first-served among equals, add a counter field and compare it when priorities tie.

Under the hood it’s a heap: adding and removing each take a few steps that grow very slowly with the size, much less work than keeping a whole list sorted. It’s what pathfinding (like Dijkstra’s algorithm), schedulers and “top 10” problems use.

A queue is “first in, first out”: people join at the back and leave from the front. You could do that with an ArrayList and orderedRemove(0), but that shifts every item each time someone leaves. std.Deque (say “deck”, short for double-ended queue) adds and removes at both ends without shifting anything:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var line: std.Deque([]const u8) = .empty;
defer line.deinit(gpa);
try line.pushBack(gpa, "Ana");
try line.pushBack(gpa, "Bo");
try line.pushBack(gpa, "Cy");
try line.pushFront(gpa, "VIP");
std.debug.print("{d} waiting, front: {s}, back: {s}\n", .{ line.len, line.front().?, line.back().? });
while (line.popFront()) |person| {
std.debug.print("serving {s}\n", .{person});
}
}

Output:

4 waiting, front: VIP, back: Cy
serving VIP
serving Ana
serving Bo
serving Cy

pushBack/popFront give you a normal queue; pushBack/popBack give you a stack; and you can mix all four. line.len is the count (a field, not a method), front() and back() peek at the ends, and at(i) reads any position. Internally it’s a ring buffer: one block of memory where the front can wrap around to the start, which is why nothing has to shift. Reach for it for job queues, breadth-first search, or an “undo” history with a size limit.

Bit sets: lots of yes/no flags, one bit each

Section titled “Bit sets: lots of yes/no flags, one bit each”

A bit set stores a set of small numbers, from 0 up to a fixed size, using a single bit per number. It answers “is number 5 in the set?” very fast and uses very little memory: a set of 1,000 numbers takes 128 bytes, while a [1000]bool takes 1,000.

When the size is known while compiling, use std.bit_set.Static(n). It needs no allocator and no deinit:

const std = @import("std");
pub fn main() void {
const days = [_][]const u8{ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
var gym: std.bit_set.Static(7) = .empty;
gym.set(0);
gym.set(2);
gym.set(4);
var weekend: std.bit_set.Static(7) = .empty;
weekend.set(5);
weekend.set(6);
std.debug.print("gym days: {d}, Wednesday? {}\n", .{ gym.count(), gym.isSet(2) });
const busy = gym.unionWith(weekend);
var free = busy.iterator(.{ .kind = .unset });
std.debug.print("free days:", .{});
while (free.next()) |i| std.debug.print(" {s}", .{days[i]});
std.debug.print("\n", .{});
}

Output:

gym days: 3, Wednesday? true
free days: Tue Thu
  • .empty starts with every bit off (.full would start with every bit on). set(i), unset(i) and toggle(i) change one bit; isSet(i) reads one; count() counts the set bits.
  • unionWith, intersectWith and differenceWith combine two sets and return a new one.
  • iterator(.{}) walks the numbers that are set, in order. .{ .kind = .unset } walks the ones that aren’t.

When the size is only known at run time, use std.bit_set.Dynamic. It needs an allocator, like every other growing thing:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const n: usize = 30;
var is_composite = try std.bit_set.Dynamic.initEmpty(gpa, n + 1);
defer is_composite.deinit(gpa);
var i: usize = 2;
while (i * i <= n) : (i += 1) {
if (is_composite.isSet(i)) continue;
var j = i * i;
while (j <= n) : (j += i) is_composite.set(j);
}
std.debug.print("primes up to {d}:", .{n});
for (2..n + 1) |k| {
if (!is_composite.isSet(k)) std.debug.print(" {d}", .{k});
}
std.debug.print("\n", .{});
}

Output:

primes up to 30: 2 3 5 7 11 13 17 19 23 29

That’s the Sieve of Eratosthenes: cross out every multiple of each prime, and what’s left are the primes. A bit set is the classic way to store the “crossed out” marks.

Enum collections: an array or set indexed by an enum

Section titled “Enum collections: an array or set indexed by an enum”

When the keys are the values of an enum, you don’t need a hash map at all. std.EnumArray holds one value per enum value, and std.EnumSet is a set of enum values (a bit set underneath):

const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() void {
var votes: std.EnumArray(Color, u32) = .initFill(0);
for ([_]Color{ .green, .red, .green, .blue, .green }) |c| {
votes.getPtr(c).* += 1;
}
var it = votes.iterator();
while (it.next()) |entry| {
std.debug.print("{t}: {d}\n", .{ entry.key, entry.value.* });
}
var liked: std.EnumSet(Color) = .empty;
liked.insert(.blue);
std.debug.print("likes blue? {}, likes red? {}\n", .{ liked.contains(.blue), liked.contains(.red) });
}

Output:

red: 1
green: 3
blue: 1
likes blue? true, likes red? false

EnumArray is really just an array with one slot per enum value, so there’s no hashing, no allocator and no deinit, and it iterates in the order the enum declares its values. {t} prints the enum value’s name. There’s also std.EnumMap, which is like EnumArray but allows a slot to be empty.

Linked lists: items that point at each other

Section titled “Linked lists: items that point at each other”

A linked list is a chain of nodes, where each node points at the next one (and, in a doubly linked list, the previous one too). Adding or removing a node anywhere is quick once you have a pointer to it, and, unlike an ArrayList, the items never move.

Zig’s linked lists are intrusive, which sounds scary but is a simple idea. The list doesn’t hold your data. Instead, you put a small Node field inside your own struct, and the list links those fields together:

const std = @import("std");
const Song = struct {
title: []const u8,
node: std.DoublyLinkedList.Node = .{},
};
pub fn main() void {
var intro: Song = .{ .title = "Intro" };
var chorus: Song = .{ .title = "Chorus" };
var outro: Song = .{ .title = "Outro" };
var playlist: std.DoublyLinkedList = .{};
playlist.append(&intro.node);
playlist.append(&outro.node);
playlist.insertAfter(&intro.node, &chorus.node);
var it = playlist.first;
while (it) |node| : (it = node.next) {
const song: *Song = @fieldParentPtr("node", node);
std.debug.print("{s}\n", .{song.title});
}
playlist.remove(&chorus.node);
std.debug.print("{d} songs left\n", .{playlist.len()});
}

Output:

Intro
Chorus
Outro
2 songs left

The new piece here is @fieldParentPtr("node", node). The list only knows about Nodes, so when you walk it you get *Node pointers. @fieldParentPtr says: “this is a pointer to the node field of some Song; give me a pointer to that whole Song.” Zig knows where the field sits inside the struct, so it just steps back to the start. The language reference on @fieldParentPtr has the details.

Why do it this way? The list never allocates anything, so append and remove can’t fail and take no allocator. One struct can even sit in two lists at once, with two node fields. The catch: you are in charge of the memory. The nodes above live on the stack, so the list must not outlive main. For nodes on the heap, you create each item and destroy it when you take it out:

const std = @import("std");
const Page = struct {
url: []const u8,
node: std.SinglyLinkedList.Node = .{},
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var history: std.SinglyLinkedList = .{};
defer {
while (history.popFirst()) |node| {
const page: *Page = @fieldParentPtr("node", node);
gpa.destroy(page);
}
}
for ([_][]const u8{ "home", "news", "sports" }) |url| {
const page = try gpa.create(Page);
page.* = .{ .url = url };
history.prepend(&page.node);
}
var it = history.first;
while (it) |node| : (it = node.next) {
const page: *Page = @fieldParentPtr("node", node);
std.debug.print("{s}\n", .{page.url});
}
}

Output:

sports
news
home

prepend adds at the front, so the newest page comes first, which is just what a “back” button wants. The defer block pops every node and destroys the Page around it, so nothing leaks.

You won’t need these in your first programs, but it’s good to know they exist:

  • std.StaticStringMap(V) is a read-only map from strings to values, built while compiling: perfect for keyword tables like .initComptime(.{ .{ "add", 1 }, .{ "rm", 2 } }). No allocator, nothing to free.
  • std.MultiArrayList(T) stores a list of structs as one array per field, so a loop that reads only one field touches less memory. It’s a tool for performance work; see Zig Performance.
  • std.BufMap and std.BufSet are string maps and sets that copy (and free) their keys for you, so the who-owns-the-keys problem goes away. They still store their allocator, the older managed style.
You need Use
A list that grows, accessed by position std.ArrayList
Look things up by key std.AutoHashMapUnmanaged, std.StringHashMapUnmanaged
Lookups plus insertion order std.array_hash_map.Auto, std.array_hash_map.String
Always take the smallest or largest next std.PriorityQueue
Add and remove at both ends (queues) std.Deque
Yes/no flags for numbers 0 to n std.bit_set.Static(n), or std.bit_set.Dynamic
One value per enum value, or a set of enum values std.EnumArray, std.EnumSet
Items that must never move, or splicing chains together std.DoublyLinkedList, std.SinglyLinkedList
A fixed table of string keys std.StaticStringMap

When in doubt, start with an ArrayList or a hash map. Switch to something special when you can say exactly which operation it makes better.

Put the numbers 5, 1, 9, 3, 7 into a priority queue that gives the largest number first, and pop them all.

Hint: the compare function returns std.math.order(a, b).invert(). You can add several at once with pushSlice(gpa, &.{ ... }).

Show solution
const std = @import("std");
fn largestFirst(_: void, a: u32, b: u32) std.math.Order {
return std.math.order(a, b).invert();
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var queue: std.PriorityQueue(u32, void, largestFirst) = .empty;
defer queue.deinit(gpa);
try queue.pushSlice(gpa, &.{ 5, 1, 9, 3, 7 });
while (queue.pop()) |n| std.debug.print("{d}\n", .{n});
}

Output:

9
7
5
3
1

invert turns .lt into .gt and the other way around, so the order flips from smallest-first to largest-first.

Use a std.bit_set.Static(26) to record which lowercase letters appear in "hello world", then print how many different letters there are and list them.

Hint: for each byte c in 'a'...'z' (check with std.ascii.isLower), call letters.set(c - 'a'). To print, iterate with iterator(.{}) and turn each index back into a letter with @as(u8, @intCast(i)) + 'a'.

Show solution
const std = @import("std");
pub fn main() void {
var letters: std.bit_set.Static(26) = .empty;
for ("hello world") |c| {
if (std.ascii.isLower(c)) letters.set(c - 'a');
}
std.debug.print("{d} different letters:", .{letters.count()});
var it = letters.iterator(.{});
while (it.next()) |i| {
const letter = @as(u8, @intCast(i)) + 'a';
std.debug.print(" {c}", .{letter});
}
std.debug.print("\n", .{});
}

Output:

7 different letters: d e h l o r w

Repeated letters just set the same bit again, so the count is the number of different letters, and the iterator lists them in alphabetical order for free.

Players take turns in a circle: put Ana, Bo and Cy in a std.Deque, then for 5 turns take the player at the front, print “turn N: name”, and put them back at the end.

Hint: const p = line.popFront().?; then try line.pushBack(gpa, p);.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var line: std.Deque([]const u8) = .empty;
defer line.deinit(gpa);
try line.pushBackSlice(gpa, &.{ "Ana", "Bo", "Cy" });
for (1..6) |turn| {
const p = line.popFront().?;
std.debug.print("turn {d}: {s}\n", .{ turn, p });
try line.pushBack(gpa, p);
}
}

Output:

turn 1: Ana
turn 2: Bo
turn 3: Cy
turn 4: Ana
turn 5: Bo

Taking from the front and adding at the back is cheap on a deque, so this works the same with three players or three million.

  • std.PriorityQueue always gives back the best item next, by your compare function. Equal items come out in no promised order.
  • std.Deque adds and removes at both ends cheaply: queues, stacks, round-robins.
  • Bit sets store yes/no for numbers 0 to n, one bit each: std.bit_set.Static(n) without an allocator, std.bit_set.Dynamic with one. (Renamed in 0.17.)
  • std.EnumArray and std.EnumSet are the simplest choice when the keys are enum values.
  • Zig’s linked lists are intrusive: put a Node field in your struct and get back to the struct with @fieldParentPtr. They never allocate; you own the nodes.
  • When unsure, use an ArrayList or a hash map, and switch only for a clear reason.

Next up: Zig Modules & Imports, splitting a program across files with @import and pub.

Quick check

1. You keep adding jobs with a priority and always want to run the most urgent one next. Which collection fits best?
2. In a Zig linked list, how do you get from a *Node back to your own struct?
3. What is the Zig 0.17 name of the bit set whose size you pick while compiling?
4. Why is a plain ArrayList often faster than a linked list, even when you insert in the middle?