Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Zig function pointers to other functions?

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:

  • Zig version: 0.10.0-dev.4588+9c0d975a0
  • M1 Mac, MAC OS Ventura
like image 431
Himujjal Avatar asked Jul 24 '26 23:07

Himujjal


1 Answers

Starting with 0.10, there are 2 ways to pass a function as an argument:

  • As a function body. Must be comptime-known.
  • As a function pointer.

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
like image 139
sigod Avatar answered Jul 28 '26 01:07

sigod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!