Type of ComptimeStringMap

Currently, I have two ComptimeStringMaps, and based on different runtime conditions. So, I have a get_map function, but I’m facing issues while writing the return type.

const ComptimeStringMap = @import("std").ComptimeStringMap;

const KV = struct {
    @"0": []const u8,
    @"1": u32,
};

const map1 = ComptimeStringMap(u32, [_]KV{
    .{ .@"0" = "foo", .@"1" = 42 },
    .{ .@"0" = "barbaz", .@"1" = 99 },
});

const map2 = ComptimeStringMap(u32, [_]KV{
    .{ .@"0" = "foo", .@"1" = 42 },
    .{ .@"0" = "barbaz", .@"1" = 99 },
});

fn get_map(cond: bool) ??? {  // here
    if (cond) {
        return map1;
    } else {
        return map2;
    }
}

I tried using @TypeOf, but my function parameters are runtime values, so I can’t use that. Is there any way to solve this? Thanks.

ComptimeStringMap returns a type, so @TypeOf(map1) would just return type:

const map = std.ComptimeStringMap(u32, .{
    .{ "abc", 1 },
    .{ "def", 2 },
});
comptime {
    @compileLog(@TypeOf(map));
}
Compile Log Output:
@as(type, type)

So you’d need a function that returns a type, but only functions that have all comptime parameters can return a type, so that won’t work (as you mentioned).

One way to go would be to write a function like this instead (or just write this logic inline where you need it):

fn getFromMap(cond: bool, key: []const u8) ?u32 {
    if (cond) {
        return map1.get(key);
    } else {
        return map2.get(key);
    }
}

Yes, I think there probably isn’t a better way. I’m going to wrap the get and has function. Thank you.