I have the following code where I try to pass in a function to another function:
const std = @import("std");
const St = struct { a: usize };
fn returnFunc(print: fn (str: []const u8, st: St) void) void {
print("Hello", St{ .a = 1 });
}
fn toTest(str: []const u8, st: St) void {
std.debug.print("{s}: {d}\n", .{str, st.a});
}
pub fn main() !void {
returnFunc(toTest);
}
But it fails to compile with the following error:
error: parameter of type 'fn([]const u8, main.St) void' must be declared comptime
Machine details:
Starting with 0.10, there are 2 ways to pass a function as an argument:
comptime-known.For example:
const std = @import("std");
fn foo(str: []const u8) void {
std.debug.print("{s}\n", .{ str });
}
fn asBody(comptime print: fn (str: []const u8) void) void {
print("hello from function body");
}
fn asPointer(print: *const fn (str: []const u8) void) void {
print("hello from function pointer");
}
pub fn main() void {
asBody(foo);
asPointer(foo);
}
This prints:
$ zig build run
hello from function body
hello from function pointer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With