#Suppliers in zig
1 messages · Page 1 of 1 (latest)
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 { ... }