I’m writing code as a hobby, and learning zig writing little toys. For one of them, I was hoping to have a function as field of a struct. My difficulty is that the function will be unique to each instance of the struct.
I would like to write something like this, but can’t find the correct way to do so:
My little example, just in case (a sort of dynamic dispatch via virtual method table, with one element in this case):
const std = @import("std");
const log = std.debug.print;
const methodPtr = *const fn(c: *Class) void;
const Class = struct {
x: u32,
m: methodPtr,
fn callMethod(i: *Class) void {
i.m(i);
}
};
pub fn main() void {
var inst1 = Class{.x = 1, .m = &m1};
var inst2 = Class{.x = 2, .m = &m2};
inst1.callMethod();
inst2.callMethod();
}
fn m1(i: *Class) void {
log("my x is {}\n", .{i.x});
log("I can do this\n", .{});
}
fn m2(i: *Class) void {
log("my x is {}\n", .{i.x});
log("I can do that\n", .{});
}
Also, when I see the words “state” and “event” close to each other,
I immediately start to guess that this is about “event driven state machines” or so.
EDSM, as I call it, is a design methodology which I advocate here and there
If you are interested you can take a look at my GitHub repos with edsm in names (nick is the same as on this forum, dee0xeed). There are various versions of the engine and, If I remember right, the most recent was here.
TBH, I do not know why I used camelCase for them, I depicted it from some code I wrote before (probably at that time I did not think right and was not realizing these should be in PascalCase).
And, BTW, here is small excerpt from /opt/zig-0.11/lib/std$ grep -rI "= \*const fn":