#Switch on strings?

1 messages · Page 1 of 1 (latest)

boreal helm
#

Hi, I would like to do switch on strings. It seems that switch construct from Zig doesn't support strings - so I was thinking about ComptimeStringMap where values are closures. But I don't know how to write it in code.

dapper grail
#

suggestion: use std.meta.stringToEnum, where you use an enum with names of all the string cases you'd want to handle

#
const Case = enum {
    fizz,
    buzz,
    @"fizz buzz",
};
const case = try std.meta.stringToEnum(Case, str);
switch (case) {
    .fizz => {},
    .buzz => {},
    .@"fizz buzz" => {},
}
#

it uses std.ComptimeStringMap under the hood

subtle jungle
#

I almost never use the meta package, but this case is too good to ignore