Trying to build a simple router, where a given function is called based on the required route, so for testing I started with the below:
// routes.zig
const std = @import("std");
//pub const LoadFunction = fn (i32) f32;
pub fn init(routeRegister: *std.StringHashMap(fn (i32) f32)) !void {
try routeRegister.put("/load", load);
}
pub fn load(i: i32) f32 {
std.log.info("file is loaded, {}", .{i});
return 0.1;
}
And in the main function I have:
var routeRegister = std.StringHashMap(fn (i32) f32).init(allocator);
try routes.init(&routeRegister);
defer routeRegister.deinit();
if (routeRegister.get(target)) |handler| {
std.debug.print("Calling handler: {s} for route: {s}\n", .{ handler, target });
///** Here I want to call the function `load` if the target route is `/load` **///
} else {
log.err("Unknown route: {s}", .{target});
return error.ErrorNoEntity;
}
[hasany@hasan-20tes1n300 src]$ zig run main.zig
/usr/lib/zig/std/hash_map.zig:539:41: error: parameter of type 'fn(i32) f32' must be declared comptime
pub fn put(self: *Self, key: K, value: V) Allocator.Error!void {
^~~~~~~~
/usr/lib/zig/std/hash_map.zig:539:41: note: use '*const fn(i32) f32' for a function pointer type
referenced by:
init: routes.zig:5:22
handleRequest: main.zig:117:19
remaining reference traces hidden; use '-freference-trace' to see all reference traces
/usr/lib/zig/std/hash_map.zig:752:24: error: function pointers must be single pointers
values: [*]V,
^
load
"which is defined at the hashmap, once I get the matched key, which is in my case /load
?You use a function body instead of a function pointer. The compiler even tells you:
hash_map.zig:539:41: note: use '*const fn(i32) f32' for a function pointer type
Second, how can I envoke the function load "which is defined at the hashmap, once I get the matched key, which is in my case /load?
Simply call it as any other function:
handler(i);