What's the equivalent of std::function in Zig?

127 Views Asked by At

How can I implement a map in Zig (v0.11.0) that associates i32 values with function references?

In C++, I would use std::function for this purpose, but I'm unable to find an equivalent in Zig. I've thoroughly searched the documentation and various online forums, but I couldn't find any information.

I'm hoping someone with great Zig experience could provide me with a solution on how to achieve this.

Any assistance would be greatly appreciated (I'm very sorry for my bad English, it's my fourth language).

1

There are 1 best solutions below

0
On

Use function pointers or function bodies.

You can also use std.ArrayHashMap to avoid implementing the map yourself. For example:

const std = @import("std");

fn foo() void {
    std.log.info("hello, world", .{});
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(gpa.deinit() == .ok);
    const allocator = gpa.allocator();

    var map = std.AutoArrayHashMap(i32, *const fn () void).init(allocator);
    defer map.deinit();
    
    try map.put(1, &foo);

    if (map.get(1)) |ptr| {
        ptr();
    }
}