Search code examples
zig

Idiomatic way to wite/pass type to generic function in ziglang


This is a much simplified version of my real issue but hopefully demonstrates my question in a concise manner.

My question is about the interface to printKeys. I have to pass in the type of the data to be printed as a comptime parameter, and the easiest way to get this is to use @TypeOf on the map at the point of calling it.

Coming from C++ this seems slightly inelegant that the type can't be inferred, although I do like being explicit too.

Is there a more idiomatic way to have a generic function in zig that doesn't need this use of @TypeOf at the point of calling, or a better way to do this in general?

const std = @import("std");

fn printKeys(comptime MapType: type, data: MapType) void {

    var iter = data.keyIterator();
    while (iter.next()) | value | {
        std.debug.print("Value is {}\n", .{value.*});
    }
}

pub fn main() !void {
    const allocator = std.heap.page_allocator;
   
    var map = std.AutoHashMap(i32, []const u8).init(allocator);
    defer map.deinit();

    try map.put(10, "ten");
    try map.put(12, "twelve");
    try map.put(5, "five");

    printKeys(@TypeOf(map), map);
}

Solution

  • use anytype. you can find more examples in zig docs (Ctrl + F) and search anytype

    fn printKeys(data: anytype) void {
        ...
    }
    
    pub fn main() !void {
        ...
        printKeys(map);
    }