如何将 Zig 函数指针传递给其他函数?

Him*_*jal 3 compiler-errors function-pointers zig

当我将一个函数传递给另一个函数时,出现以下错误?

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);
}
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

error: parameter of type 'fn([]const u8, main.St) void' must be declared comptime
Run Code Online (Sandbox Code Playgroud)

机器详细信息: Zig 版本:0.10.0-dev.4588+9c0d975a0 M1 Mac、MAC OS Ventura

sig*_*god 6

从 0.10 开始,有两种方法将函数作为参数传递

  • 作为函数体。必须是comptime已知的。
  • 作为函数指针。

例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

这打印:

$ zig build run
hello from function body
hello from function pointer
Run Code Online (Sandbox Code Playgroud)