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

问题描述 投票:0回答:2

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

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

compiler-errors function-pointers zig
2个回答
4
投票

从 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

0
投票

回答我自己的问题。

我只需要将

returnFunc
的函数签名更改为:

fn returnFunc(comptime print: fn (str: []const u8, st: St) void) void {
    print("Hello", St{ .a = 1 });
}
© www.soinside.com 2019 - 2024. All rights reserved.