I want to use a function pointer as a struct field to have a runtime choice of an executed method.
For example, I want this code to print 010
:
const std = @import("std");
fn Foo() type {
return struct {
const Self = @This();
const doThingFunc = fn (self: *Self) u1;
doThing: doThingFunc = Self.doZero,
fn doZero(self: *Self) u1 {
self.doThing = Self.doOne;
return 0;
}
fn doOne(self: *Self) u1 {
self.doThing = Self.doZero;
return 1;
}
};
}
pub fn main() void {
var foo = Foo(){};
std.debug.print("{d}{d}{d}", .{ foo.doThing(), foo.doThing(), foo.doThing() });
}
But I get this error instead, which makes no sense for me:
An error occurred:
example.zig:9:19: error: parameter of type '*example.Foo()' must be declared comptime
fn doZero(self: *Self) u1 {
^~~~~~~~~~~
What is a correct way to implement desired behavior with function pointers in Zig?