typestar

StringHashMap in Zig

A harbor registry: string keys, integer berths, and an iterator over the keys.

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.DebugAllocator(.{}){};
    defer _ = gpa.deinit();
    const alloc = gpa.allocator();

    // Keys are string slices; the map borrows them.
    var moorings = std.StringHashMap(u32).init(alloc);
    defer moorings.deinit();

    try moorings.put("Persephone", 9);
    try moorings.put("Skua", 4);

    std.debug.print("Skua at berth {?d}\n", .{moorings.get("Skua")});
    std.debug.print("ships registered: {d}\n", .{moorings.count()});
    var it = moorings.keyIterator();
    while (it.next()) |ship| std.debug.print("- {s}\n", .{ship.*});
}

How it works

  1. StringHashMap(u32).init(alloc) keys entries by string slices it borrows.
  2. put inserts; get returns an optional the {?d} format prints as-is.
  3. keyIterator walks the registered ships; .* reads each key pointer.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
569
Tokens
184
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 170 seconds.

Type this snippet

Step 3 of 3 in The standard library, step 24 of 27 in Language basics.

← Previous Next →