0

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);
}
jcoder
  • 29,554
  • 19
  • 87
  • 130

1 Answers1

2

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);
}
Ali Chraghi
  • 613
  • 6
  • 16
  • 1
    Thank you, I'd seen that and wrongly assumed that anytype was a run time variant container like std::any in c++ but it seems on reading the docs again it's a generic placeholder type which is exactly what I wanted. – jcoder Jan 08 '22 at 13:15