I wanted to play around with HashMaps and used the example from the Zig documentation (pasted below). The example works great, but taking the example and putting it in a main function does not work. I have to pass in an allocator that works outside of testing.
I have tried a number of things, like reading a bit about allocators and trying to pass in different allocators, but I cannot figure out how to make it work.
My questions:
- can someone give me a working example where a HashMap is created in a main function with a memory allocator?
- what are good resources on better understanding memory allocators? I am used to garbage collected languages and find that the existing explanations on the topic in the docs don't really make me understand how to work with them
test "hashing" {
const Point = struct { x: i32, y: i32 };
var map = std.AutoHashMap(u32, Point).init(
test_allocator,
);
defer map.deinit();
try map.put(1525, .{ .x = 1, .y = -4 });
try map.put(1550, .{ .x = 2, .y = -3 });
try map.put(1575, .{ .x = 3, .y = -2 });
try map.put(1600, .{ .x = 4, .y = -1 });
try expect(map.count() == 4);
var sum = Point{ .x = 0, .y = 0 };
var iterator = map.iterator();
while (iterator.next()) |entry| {
sum.x += entry.value_ptr.x;
sum.y += entry.value_ptr.y;
}
try expect(sum.x == 10);
try expect(sum.y == -10);
}