-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve std.StaticStringMap.initComptime
#19936
Comments
This change would make building the key value list pragmatically much more complicated, you would need to use |
The reason why const Enum = ErrorEnum(ErrorSet);
const error_to_enum = error_to_enum: {
const ErrorEnumItem = std.meta.Tuple(&[_]type{ []const u8, Enum });
comptime var error_to_enum_list: [es.len]ErrorEnumItem = undefined;
inline for (0.., es) |i, err| {
error_to_enum_list[i] = .{
err.name,
@field(Enum, err.name),
};
}
break :error_to_enum std.StaticStringMap(Enum).initComptime(&error_to_enum_list);
}; |
My real issue with the current API is that nothing stops you from passing multiple tuples with the same key. What do you think the following code prints? pub fn main() !void {
const Foo = enum { a, b };
const NameMap = std.StaticStringMap(Foo).initComptime(.{
.{ "c89", .b },
.{ "c89", .a },
});
std.debug.print("{}\n", .{ NameMap.get("c89").? });
} The answer may surprise you. This kind of mistake is a common copy-paste error.
No usage in the stdlib builds a key value list at comptime. Every usage is truly a static string map. I consider @Pyrolistical's use case an exception rather than the norm. If you really want convenient support for building a list from a |
the compiler not doing it, doesn't mean its not done out in the wild. I would expect the example above to compile error (through the use of a comptime assertion) |
@clickingbuttons here it usage in zig-gamedev, of which I wrote: |
That's just not true Lines 25 to 33 in 6a65561
|
You're correct @silversquirl, I missed that one! My point still stands that the majority of usage, and I'd argue the intended usage is passing a static map-like structure rather than a built list. |
there are two current limits on identifiers that i am aware of:
|
I think @paperdave 's example is enough of a reason not make a map API the default. I'll open a separate issue to make duplicate keys a comptime error. |
Status quo uses an anonymous struct of
struct{ []const u8, T }
:I propose a more map-like anonymous
struct
:I don't think this is a design issue as long as Zig identifiers can be any arbitrary bytes.
Edit: This would also prevent accidentally initializing the same key twice at compile time.
The text was updated successfully, but these errors were encountered: