Why doesn't the Zig standard library provide constraint functions?

While working on HashMapContext, I encountered a question: What exactly is inside a Context?

If the standard library provided corresponding constraint functions, I could do something like this:

const SomeHashMapContext = struct {
    comptime {
        std.HashMap.constrainContext(@This());
    }
}

This way, I could easily identify what’s missing in this Context.

I believe many people share similar confusion, and it’s not just limited to the HashMapContext issue.

the docs describe it

/// Context must be a struct type with two member functions:
///   hash(self, K) u64
///   eql(self, K, K) bool

And you will get a compile error if they are missing or have the wrong definitions, though they might be confusing if you are not used to duck typing.

1 Like

Well, by examining the Context in StringHashMap, I’ve certainly figured out what is needed in the Context. However, there are still some issues:

  • Relying on compilation errors during calls to check is too primitive, and the information is insufficient.
  • This problem isn’t unique to HashMapContext—there are many cryptic parameters in the standard library.

I’m hobbying on a module that might do the kind of things you seem to ask. I haven’t figured out how to make it work with the new formatting yet but I’ll get there.

2 Likes