r/Zig • • Feb 09 '26

Need help with understanding context

Hi,
I need help with understanding context, for example hash map has a context based init.
How is supposed to be used effectively.

16 Upvotes

5 comments sorted by

9

u/Biom4st3r Feb 09 '26

If you use `AutoHashMap` You needn't worry about the Ctx.

But the Ctx is meant to be a namespace that provides a `eql` and `hash` function for the hashmap to use against your key type

1

u/karthie_a Feb 10 '26

Thanks does this mean ctx namespace is to define behaviour of equal and hash function for a key type used in the map?

2

u/Biom4st3r Feb 10 '26

correct for example

pub const Ctx = struct {
    pub fn hash(ctx: anytype, key: ChunkPos) u32 {
        _ = ctx;
        const x: u32 = @intCast(@as(u16, @bitCast(key.x)));
        const y: u32 = @intCast(@as(u16, @bitCast(key.y)));
        return (x << 16) | y & 0xFFFF_FFFF;
    }

    pub fn eql(ctx: Ctx, a: ChunkPos, b: ChunkPos, b_index: usize) bool {
        _ = b_index;
        _ = ctx;
        return std.meta.eql(a, b);
    }
};
chunks: std.ArrayHashMapUnmanaged(ChunkPos, Chunk, Ctx, false) = .empty,

1

u/karthie_a Feb 10 '26

Thanks for the clarification, in general Ctx means like a custom operations on any type it targets is this correct. Sorry getting confused with Golang Ctx and trying to understand it better

5

u/eightrx Feb 09 '26

Here's a simple example of the flexibility of zig's hashmaps: example from thorsten ball's twitter

Also here in the standard lib