#Suppliers in zig

1 messages · Page 1 of 1 (latest)

upper merlin
#

Is there a way to pass in a method that creates a certain struct and returns it, then run that method dynamically thru another method without ever knowing the method?

Pseudo code example:

pub fn supply(suppplier: Function<i32>) i32 {
return supplier();
}

bright musk
#

yes. you can pass a function pointer:

pub fn supply(supplier: *const fn() i32) i32 {
    return supplier();
}
#

because Zig does not support closures, this won't work if the supplier needs to capture extra data for the computation. to account for that you can also pass a context:

pub fn supply(context: anytype, supplier: *const fn(@TypeOf(context)) i32) i32 {
    return supplier(context);
}
#

this pass-a-context-of-any-type-and-a-corresponding-function is a pattern that you see quite often in Zig, for example, here's std.mem.sort's signature:

pub fn sort(
    comptime T: type,
    items: []T,
    context: anytype,
    comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool,
) void { ... }