HashMap

Generic hash map implementation with string keys

zig (0.11) 2025-11-12 hashmap dictionary collections key-value

Description

A hash map implementation using Zig’s standard library HashMap. Provides type-safe key-value storage with string keys.

Features

  • String key hashing
  • Type-safe values
  • Insert/Get/Remove operations
  • Iteration support

Code

RAW
const std = @import("std");pub fn HashMap(comptime V: type) type {    return struct {        map: std.StringHashMap(V),        allocator: std.mem.Allocator,                const Self = @This();                pub fn init(allocator: std.mem.Allocator) Self {            return Self{                .map = std.StringHashMap(V).init(allocator),                .allocator = allocator,            };        }                pub fn put(self: *Self, key: []const u8, value: V) !void {            try self.map.put(key, value);        }                pub fn get(self: *const Self, key: []const u8) ?V {            return self.map.get(key);        }                pub fn remove(self: *Self, key: []const u8) ?V {            return self.map.fetchRemove(key);        }                pub fn contains(self: *const Self, key: []const u8) bool {            return self.map.contains(key);        }                pub fn size(self: *const Self) usize {            return self.map.count();        }                pub fn clear(self: *Self) void {            self.map.clearAndFree();        }                pub fn deinit(self: *Self) void {            self.map.deinit();        }    };}
RAW
const std = @import("std");const HashMap = @import("hash_map.zig").HashMap;pub fn main() !void {    var gpa = std.heap.GeneralPurposeAllocator(.{}){};    defer _ = gpa.deinit();    const allocator = gpa.allocator();        var map = HashMap(i32).init(allocator);    defer map.deinit();        try map.put("apple", 10);    try map.put("banana", 20);    try map.put("cherry", 30);        if (map.get("apple")) |value| {        std.debug.print("Value for 'apple': {}\n", .{value});    }        std.debug.print("Size: {}\n", .{map.size()});        _ = map.remove("banana");    std.debug.print("Size after remove: {}\n", .{map.size()});}

Comments

No comments yet. Be the first to comment!