Hello!
I’m new to Zig. I was wondering if there are pointers to functions in zig. But I didn’t find the answer. I tried @Frame, but apparently it’s for asynchronous functions, and it’s not what I need at all.
So how do I take a pointer to a function in Zig?
I think you should be able to… just take the pointer to a function with &functionName
?
See: Compiler Explorer
If you have a specific problem you’re trying to solve that involves function pointers, maybe try explaining the larger context and it’d be easier to give suggestions about it.
I haven’t used function pointers much, but this little example shows what I know about function pointers:
const print = @import("std").debug.print;
fn aFunction(num: i32) i32 {
return num + 1;
}
const S = struct { ptr: fn (i32) i32 };
pub fn main() void {
var s: S = .{ .ptr = aFunction };
print("{}\n", .{s.ptr(5)});
}
Right now, functions are implicitly pointers, so all you need to do is use the name of a function in an assignment to a function pointer variable (or here a member of a struct). I just chose to use a struct for fun, and it also shows how to annotate the type.
Note that the self-hosted compiler will very likely be changing this syntax. See issue 1717 and issue 6966. So when that change comes, I am pretty sure that what @jmc said about using &functionName
will be required, which makes more sense honestly.
I handled it. Thanks!