Zig ArrayList & HashMap
Arrays have a fixed size. When you need a collection that grows at runtime, the standard library offers std.ArrayList (a growable array, like Rust's Vec or C++'s std::vector) and a family of hash maps. Both store their data on the heap, so they work with an allocator.
Note: Zig 0.15 changed these containers to the unmanaged style: the container does not remember its allocator; you pass the allocator to every method that may allocate or free. Older tutorials show
ArrayList(T).init(allocator)andlist.append(x)— in 0.15 that API lives on asstd.array_list.Managedbut is deprecated.
ArrayList basics
const std = @import("std");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var list: std.ArrayList(i32) = .empty;
defer list.deinit(allocator);
try list.append(allocator, 10);
try list.append(allocator, 20);
try list.appendSlice(allocator, &.{ 30, 40, 50 });
try list.insert(allocator, 0, 5);
std.debug.print("items: {any}\n", .{list.items});
std.debug.print("len: {d}, first: {d}\n", .{ list.items.len, list.items[0] });
const last = list.pop(); // optional: null when empty
const removed = list.orderedRemove(1); // keeps order, shifts the rest
std.debug.print("popped {?d}, removed {d}\n", .{ last, removed });
std.debug.print("items: {any}\n", .{list.items});
}items: { 5, 10, 20, 30, 40, 50 }
len: 6, first: 5
popped 50, removed 10
items: { 5, 20, 30, 40 }
The elements live in list.items, an ordinary slice, so loops, std.mem functions and sorting all work on it.
| Method | Allocator needed? | Effect |
|---|---|---|
append(a, x) |
yes | add at the end |
appendSlice(a, xs) |
yes | add several |
insert(a, i, x) |
yes | insert at index i |
pop() |
no | remove last, returns ?T |
orderedRemove(i) |
no | remove, keep order |
swapRemove(i) |
no | remove fast, last element fills the gap |
clearRetainingCapacity() |
no | empty it, keep the memory |
toOwnedSlice(a) |
yes | hand the items to the caller as a slice |
deinit(a) |
yes | free the memory |
Building strings with ArrayList(u8)
An ArrayList(u8) is Zig's string builder. print formats directly into it:
const std = @import("std");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
var csv: std.ArrayList(u8) = .empty;
const rows = [_]struct { name: []const u8, qty: u32 }{
.{ .name = "bolts", .qty = 120 },
.{ .name = "nuts", .qty = 75 },
};
try csv.appendSlice(a, "name,qty\n");
for (rows) |r| {
try csv.print(a, "{s},{d}\n", .{ r.name, r.qty });
}
std.debug.print("{s}", .{csv.items});
std.debug.print("({d} bytes)\n", .{csv.items.len});
}name,qty
bolts,120
nuts,75
(27 bytes)
Hash maps
A hash map stores key → value pairs with fast lookup. Pick the variant by key type:
| Type (unmanaged) | Keys |
|---|---|
std.AutoHashMapUnmanaged(K, V) |
integers, enums, simple structs |
std.StringHashMapUnmanaged(V) |
[]const u8 strings |
std.AutoArrayHashMapUnmanaged(K, V) |
like Auto, but remembers insertion order |
std.StringArrayHashMapUnmanaged(V) |
like String, but remembers insertion order |
(The managed versions without Unmanaged — e.g. std.StringHashMap(V).init(allocator) — still exist in 0.15 and store the allocator for you.)
const std = @import("std");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var stock: std.StringHashMapUnmanaged(u32) = .empty;
defer stock.deinit(allocator);
try stock.put(allocator, "apple", 12);
try stock.put(allocator, "pear", 4);
try stock.put(allocator, "apple", 15); // overwrites
std.debug.print("apples: {?d}\n", .{stock.get("apple")});
std.debug.print("kiwis: {?d}\n", .{stock.get("kiwi")});
std.debug.print("has pear: {}, count: {d}\n", .{ stock.contains("pear"), stock.count() });
if (stock.getPtr("pear")) |p| p.* += 10;
_ = stock.remove("apple");
std.debug.print("pears now: {d}, count: {d}\n", .{ stock.get("pear").?, stock.count() });
}apples: 15
kiwis: null
has pear: true, count: 2
pears now: 14, count: 1
Warning: A
StringHashMapstores the key slice, not a copy of the text. If the key points into a buffer that you later overwrite or free, the map breaks. Duplicate such keys withallocator.dupefirst.
Counting with getOrPut
getOrPut looks up a key and inserts it if missing, in one hash operation. It is the idiomatic way to count things. Plain hash maps iterate in an unpredictable order, so sort the results (or use an ArrayHashMap) when order matters:
const std = @import("std");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var counts: std.AutoArrayHashMapUnmanaged(u8, u32) = .empty;
defer counts.deinit(allocator);
for ("mississippi") |c| {
const entry = try counts.getOrPut(allocator, c);
if (!entry.found_existing) entry.value_ptr.* = 0;
entry.value_ptr.* += 1;
}
// insertion order: m, i, s, p
var it = counts.iterator();
while (it.next()) |e| {
std.debug.print("{c}={d} ", .{ e.key_ptr.*, e.value_ptr.* });
}
std.debug.print("\n", .{});
// sorted by key: copy the keys, sort the copy, look each one up
var keys: [16]u8 = undefined;
const n = counts.count();
@memcpy(keys[0..n], counts.keys());
std.mem.sort(u8, keys[0..n], {}, std.sort.asc(u8));
for (keys[0..n]) |k| std.debug.print("{c}:{d} ", .{ k, counts.get(k).? });
std.debug.print("\n", .{});
}m=1 i=4 s=4 p=2
i:4 m:1 p:2 s:4
Test yourself
In Zig 0.15, how do you add an item to list: std.ArrayList(i32)?
- list.append(5)
- try list.append(allocator, 5)
- list.push(5)
- list += 5
Where are the elements of an ArrayList stored and accessed?
- list.data
- list.items, a slice
- list.array
- list[0] only
Which map keeps keys in insertion order?
- AutoHashMap
- StringHashMap
- AutoArrayHashMap
- None of them