Skip to content

Zig HashMap

An ArrayList finds things by position: item 0, item 1, item 2. Often you want to find things by name instead: the price of “apples”, the user with ID 1042, how many times a word appears. That’s what a hash map is for. You store key and value pairs, and later you ask “what’s the value for this key?” and get the answer quickly, however many pairs there are. Python calls it a dict, JavaScript has Map, Rust has HashMap.

Here’s a map from a product ID (a number) to how many are in stock:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var stock: std.AutoHashMapUnmanaged(u32, u16) = .empty;
defer stock.deinit(gpa);
try stock.put(gpa, 1001, 12);
try stock.put(gpa, 1002, 0);
try stock.put(gpa, 1003, 7);
std.debug.print("{d} products\n", .{stock.count()});
std.debug.print("1003 has {?d} in stock\n", .{stock.get(1003)});
std.debug.print("9999 has {?d} in stock\n", .{stock.get(9999)});
}

Output:

3 products
1003 has 7 in stock
9999 has null in stock

It looks a lot like an ArrayList, on purpose:

  • std.AutoHashMapUnmanaged(u32, u16) is the type: keys are u32, values are u16. “Auto” means Zig works out how to hash the key type for you.
  • It starts as .empty and is freed with defer stock.deinit(gpa).
  • put(gpa, key, value) stores a pair. It takes the allocator and needs try, because the map may need more memory.
  • get(key) returns an optional, ?u16: the value if the key is there, null if it isn’t. A missing key is a normal answer, not an error.
  • count() is how many pairs are in the map.

“Unmanaged” means the map doesn’t keep an allocator inside, exactly like ArrayList: you pass one to every call that may allocate. More on the name at the end of this page.

Because get returns an optional, you handle the “not there” case the same ways you learned for optionals: if with a capture, orelse for a default, or contains when you only care whether the key exists.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var prices: std.AutoHashMapUnmanaged(u32, f32) = .empty;
defer prices.deinit(gpa);
try prices.put(gpa, 1, 2.5);
try prices.put(gpa, 2, 0.99);
if (prices.get(1)) |price| {
std.debug.print("item 1 costs {d}\n", .{price});
} else {
std.debug.print("item 1 isn't for sale\n", .{});
}
const p3 = prices.get(3) orelse 0;
std.debug.print("item 3 costs {d}\n", .{p3});
std.debug.print("has item 2? {}\n", .{prices.contains(2)});
if (prices.getPtr(2)) |price| price.* *= 2;
std.debug.print("item 2 now costs {d}\n", .{prices.get(2).?});
}

Output:

item 1 costs 2.5
item 3 costs 0
has item 2? true
item 2 now costs 1.98

get hands you a copy of the value. To change a value inside the map, use getPtr, which gives a pointer (?*f32) you can write through. The last line uses .? because we just checked that item 2 exists; on a missing key .? would panic.

put on a key that’s already there replaces the old value. There’s no error and no duplicate: a map holds each key once. remove deletes a key and tells you whether it was there:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var ages: std.AutoHashMapUnmanaged(u32, u8) = .empty;
defer ages.deinit(gpa);
try ages.put(gpa, 7, 30);
try ages.put(gpa, 7, 31);
std.debug.print("count: {d}, age: {?d}\n", .{ ages.count(), ages.get(7) });
std.debug.print("removed 7? {}\n", .{ages.remove(7)});
std.debug.print("removed 7 again? {}\n", .{ages.remove(7)});
std.debug.print("count: {d}\n", .{ages.count()});
}

Output:

count: 1, age: 31
removed 7? true
removed 7 again? false
count: 0

If you also want the value you removed, fetchRemove(key) returns the old key and value together (as an optional KV with fields .key and .value).

A very common job: count how often each thing appears. The slow way is get, then put, which looks the key up twice. getOrPut does it in one step. It finds the key’s slot, creating an empty one if the key is new, and tells you which happened:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const rolls = [_]u8{ 3, 6, 3, 1, 6, 6, 2, 3, 6 };
var counts: std.AutoHashMapUnmanaged(u8, u32) = .empty;
defer counts.deinit(gpa);
for (rolls) |roll| {
const entry = try counts.getOrPut(gpa, roll);
if (!entry.found_existing) {
entry.value_ptr.* = 0;
}
entry.value_ptr.* += 1;
}
for (1..7) |face| {
const n = counts.get(@intCast(face)) orelse 0;
std.debug.print("{d}: {d}\n", .{ face, n });
}
}

Output:

1: 1
2: 1
3: 3
4: 0
5: 0
6: 4

getOrPut returns a small struct with three things you’ll use:

  • found_existing is true if the key was already in the map.
  • value_ptr points at the value’s slot. For a new key the slot is undefined, so you must set it (here to 0) before you add to it.
  • key_ptr points at the stored key.

There’s a shortcut for the “start at a default” part: try counts.getOrPutValue(gpa, roll, 0) fills new slots with 0 for you and returns the entry, so the loop body becomes (try counts.getOrPutValue(gpa, roll, 0)).value_ptr.* += 1;.

To visit every pair, ask the map for an iterator and call next() until it returns null:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var colors: std.StringHashMapUnmanaged([]const u8) = .empty;
defer colors.deinit(gpa);
try colors.put(gpa, "red", "#ff0000");
try colors.put(gpa, "green", "#00ff00");
try colors.put(gpa, "blue", "#0000ff");
try colors.put(gpa, "black", "#000000");
try colors.put(gpa, "white", "#ffffff");
var it = colors.iterator();
while (it.next()) |entry| {
std.debug.print("{s} is {s}\n", .{ entry.key_ptr.*, entry.value_ptr.* });
}
}

Output:

green is #00ff00
blue is #0000ff
black is #000000
white is #ffffff
red is #ff0000

Look at the order: it’s not the order we added them. A hash map puts each key wherever its hash says, so the loop order looks random. It’s the same every time you run this exact program, but adding or removing keys, or a newer Zig, can change it. Never rely on it. If you need insertion order, use the map from the next lesson, Zig ArrayHashMap & Sets. If you need sorted output, copy the keys into a list and sort them (Zig Sorting & Searching).

Each entry has key_ptr and value_ptr, pointers into the map, so entry.value_ptr.* += 1 changes the value in place. If you only need one side, keyIterator() and valueIterator() give you just the key pointers or just the value pointers. And don’t add or remove keys while you’re looping: the docs say any change to the map makes live iterators invalid.

The colors example used std.StringHashMapUnmanaged, a map whose keys are strings ([]const u8). You need it because AutoHashMap refuses slices as keys:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var m: std.AutoHashMapUnmanaged([]const u8, u8) = .empty;
defer m.deinit(gpa);
try m.put(gpa, "a", 1);
}
lib/std/hash_map.zig:15:13: error: std.hash.autoHash does not allow slices here ([]const u8) because the intent is unclear. Consider using std.StringHashMap for hashing the contents of []const u8. Alternatively, consider using std.hash.autoHashStrat or providing your own hash function instead.

Why is the intent “unclear”? A slice is a pointer plus a length. Zig can’t guess whether you want two keys to match when they point at the same memory or when they hold the same bytes. For text you almost always mean “same bytes”, and that’s exactly what StringHashMap does: it hashes and compares the contents.

Here’s the word counter everyone writes sooner or later:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var counts: std.StringHashMapUnmanaged(u32) = .empty;
defer counts.deinit(gpa);
const text = "the cat and the dog and the bird";
var words = std.mem.tokenizeScalar(u8, text, ' ');
while (words.next()) |word| {
const entry = try counts.getOrPutValue(gpa, word, 0);
entry.value_ptr.* += 1;
}
std.debug.print("the: {d}\n", .{counts.get("the").?});
std.debug.print("and: {d}\n", .{counts.get("and").?});
std.debug.print("cat: {d}\n", .{counts.get("cat").?});
std.debug.print("{d} different words\n", .{counts.count()});
}

Output:

the: 3
and: 2
cat: 1
5 different words

tokenizeScalar splits the text on spaces (you met it in Zig Strings in Depth), and each word is counted with getOrPutValue.

This is the part of hash maps that catches almost everyone. A StringHashMap stores the key slice, not a copy of the bytes. The comment in the standard library says it plainly: “Key memory is managed by the caller.” So the bytes have to stay alive and unchanged for as long as the key is in the map.

In the word counter that’s fine: every word is a slice of text, a string literal that lives for the whole program. But watch what happens when the keys are built in a reused buffer:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var seats: std.StringHashMapUnmanaged(u32) = .empty;
defer seats.deinit(gpa);
var buf: [16]u8 = undefined;
for (1..4) |row| {
const name = try std.mem.print(&buf, "row-{d}", .{row});
try seats.put(gpa, name, @intCast(row * 10));
}
std.debug.print("count: {d}\n", .{seats.count()});
std.debug.print("row-1: {?d}\n", .{seats.get("row-1")});
var it = seats.keyIterator();
while (it.next()) |key| std.debug.print("key: {s}\n", .{key.*});
}

Output:

count: 3
row-1: null
key: row-3
key: row-3
key: row-3

All three keys are slices of the same buf, and buf now says row-3. The map is broken: row-1 can’t be found, and the “three” keys all read the same. No error, no crash, just wrong answers.

The fix is to give the map its own copy of each key with dupe, and free those copies before the map goes away:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var seats: std.StringHashMapUnmanaged(u32) = .empty;
defer {
var keys = seats.keyIterator();
while (keys.next()) |key| gpa.free(key.*);
seats.deinit(gpa);
}
var buf: [16]u8 = undefined;
for (1..4) |row| {
const name = try std.mem.print(&buf, "row-{d}", .{row});
const entry = try seats.getOrPut(gpa, name);
if (!entry.found_existing) {
entry.key_ptr.* = try gpa.dupe(u8, name);
}
entry.value_ptr.* = @intCast(row * 10);
}
std.debug.print("count: {d}\n", .{seats.count()});
std.debug.print("row-1: {?d}\n", .{seats.get("row-1")});
std.debug.print("row-3: {?d}\n", .{seats.get("row-3")});
}

Output:

count: 3
row-1: 10
row-3: 30

Two things to notice:

  • getOrPut looks the key up with the temporary name, and only for a new key do we copy it and store the copy in key_ptr. If the key already exists, the map keeps its old copy and we don’t allocate a second one.
  • The defer block frees every key before deinit. The map doesn’t free keys or values for you; it only frees its own table.

You’ll see both names. They’re the same map; the difference is where the allocator lives:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
// Unmanaged: you pass the allocator to each call.
var a: std.AutoHashMapUnmanaged(u8, u8) = .empty;
defer a.deinit(gpa);
try a.put(gpa, 1, 10);
// Managed: the map keeps the allocator you gave to init.
var b: std.AutoHashMap(u8, u8) = .init(gpa);
defer b.deinit();
try b.put(1, 10);
std.debug.print("{?d} {?d}\n", .{ a.get(1), b.get(1) });
}

Output:

10 10

Both exist in Zig 0.17, and the language reference’s example of a set still uses the managed AutoHashMap(...).init(...). But the standard library is moving everything to the unmanaged style: ArrayList switched in 0.15, and the 0.16.0 release notes say the variant without the allocator field “is more versatile and the other one should be removed”. So this site uses the Unmanaged versions, which also match how ArrayList works. If you find managed code, it’s easy to read: same methods, minus the allocator argument.

Make a StringHashMapUnmanaged([]const u8) with three names and phone numbers (all string literals). Look up one name that exists and one that doesn’t, printing not found for the missing one.

Hint: const number = book.get("Zoe") orelse "not found";. String literals live forever, so no dupe is needed.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var book: std.StringHashMapUnmanaged([]const u8) = .empty;
defer book.deinit(gpa);
try book.put(gpa, "Ana", "555-0101");
try book.put(gpa, "Bo", "555-0199");
try book.put(gpa, "Cy", "555-0123");
for ([_][]const u8{ "Bo", "Zoe" }) |name| {
const number = book.get(name) orelse "not found";
std.debug.print("{s}: {s}\n", .{ name, number });
}
}

Output:

Bo: 555-0199
Zoe: not found

Keys and values are both slices of string literals, which live for the whole program, so the map can safely keep them.

Count how many times each letter appears in "mississippi" with an AutoHashMapUnmanaged(u8, u32), then print the counts for m, i, s and p.

Hint: loop with for (word) |c| and use getOrPutValue(gpa, c, 0).

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var counts: std.AutoHashMapUnmanaged(u8, u32) = .empty;
defer counts.deinit(gpa);
for ("mississippi") |c| {
const entry = try counts.getOrPutValue(gpa, c, 0);
entry.value_ptr.* += 1;
}
for ("misp") |c| {
std.debug.print("{c}: {d}\n", .{ c, counts.get(c).? });
}
}

Output:

m: 1
i: 4
s: 4
p: 2

A u8 is a plain number, so AutoHashMap can hash it with no help. Looping over a string literal gives you its bytes one by one.

Make a struct Point with x: i32 and y: i32, and use it as a key: store '#' at a few points in an AutoHashMapUnmanaged(Point, u8), then check whether .{ .x = 1, .y = 2 } and .{ .x = 5, .y = 5 } are walls.

Hint: structs made only of numbers work as keys in AutoHashMap (Zig hashes each field). Use contains.

Show solution
const std = @import("std");
const Point = struct { x: i32, y: i32 };
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var grid: std.AutoHashMapUnmanaged(Point, u8) = .empty;
defer grid.deinit(gpa);
try grid.put(gpa, .{ .x = 0, .y = 0 }, '#');
try grid.put(gpa, .{ .x = 1, .y = 2 }, '#');
try grid.put(gpa, .{ .x = -3, .y = 4 }, '#');
for ([_]Point{ .{ .x = 1, .y = 2 }, .{ .x = 5, .y = 5 } }) |p| {
std.debug.print("({d}, {d}) is a wall: {}\n", .{ p.x, p.y, grid.contains(p) });
}
}

Output:

(1, 2) is a wall: true
(5, 5) is a wall: false

A map keyed by points is a handy way to store a big, mostly empty grid: you only pay for the cells that hold something, and negative coordinates just work.

  • A hash map stores key and value pairs and finds a value by its key quickly.
  • std.AutoHashMapUnmanaged(K, V) works for number, enum and plain struct keys; std.StringHashMapUnmanaged(V) is for string keys. Start with .empty, free with deinit(gpa).
  • put adds or replaces, get returns an optional copy, getPtr a pointer, remove returns whether the key was there.
  • getOrPut and getOrPutValue do “find or create” in one lookup, perfect for counting.
  • Iteration order is not guaranteed. Don’t change the map while you iterate.
  • A string-keyed map doesn’t copy keys. dupe them if the bytes might change or go away, and free them before deinit.

Next up: Zig ArrayHashMap & Sets, maps that remember insertion order, and maps used as sets.

Quick check

1. What does map.get(key) return when the key is not in the map?
2. You want a map from usernames ([]const u8) to scores. Which type fits?
3. You loop over a hash map with iterator(). In what order do the pairs come out?
4. You build each key in a reused [32]u8 buffer and put it into a StringHashMap. What goes wrong?