当我将一个函数传递给另一个函数时,出现以下错误?
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);
}
返回以下错误:
error: parameter of type 'fn([]const u8, main.St) void' must be declared comptime
机器详情: Zig版本:0.10.0-dev.4588+9c0d975a0 M1 Mac,MAC OS Ventura
从 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);
}
打印:
$ zig build run
hello from function body
hello from function pointer
回答我自己的问题。
我只需要将
returnFunc
的函数签名更改为:
fn returnFunc(comptime print: fn (str: []const u8, st: St) void) void {
print("Hello", St{ .a = 1 });
}