StringHashMap

std.StringHashMap implements a hash table that can be used with string keys.

This example shows just the basics. For more, see AutoHashMap, which has the same functionality but for different key types.

const std = @import("std");
const print = std.debug.print;

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

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

    try map.put("one", 1);
    try map.put("two", 2);
    try map.put("three", 3);

    var iterator = map.iterator();
    while (iterator.next()) |entry|
        print("{s} => {}\n", .{
            entry.key_ptr.*,
            entry.value_ptr.*,
        });
}
$ zig run stringhashmap.zig 
one => 1
three => 3
two => 2

One thing to keep in mind is that StringHashMap is really just a map with []u8 keys. It doesn’t account for Unicode equivalence or check that keys are valid UTF-8.

Next example: HashMap.