Take a struct SomeStruct that contain a function "prototype" {x : fn(f32) f32,}
Next, imagine two functions: "fn afunc(x : f32) f32{..}" and "fn bfunc(x : f32) f32 {..}"
Assume the behavior of afunc and bfunc are completely different despite their equal parameters and return types.
Later, SomeStruct can be instantiated with either "afunc" or "bfunc" in place of x.
Problem: This goes against the ideal of explicitness in zig. In one aspect, zig structs (at version 0.4) have similarities with abstract classes in java.
Proposed alternative: Introduce interfaces into the zig language where the "abstract functions" feature can be moved. Then zig can be kept more explicit with "interface-implementing-structs" and normal types being visually distinct when referenced, e.g with surrounding angle brackets.
fn normalstruct(param : RandomStream) Output { ... }
fn ifaceImplementation(param : <IRandomStream>) Output { ... }
Related: https://github.com/ziglang/zig/issues/1268, https://github.com/ziglang/zig/issues/1669
Mockup of alternative with zig interfaces: https://gist.github.com/user00e00/85f106624557b718673d51a8458dbab8
Another alternative would be to make function definitions expressions (#1717) and use some variation of distinct types (#1595) to do something like this:
const IFoo = @distinct(fn(f32)f32);
pub const SomeStruct = struct {
x: IFoo,
};
pub const aFunc: IFoo = fn(x: f32) f32 { ... };
pub const bFunc = fn(x: f32) f32 { ... };
const my_instance = SomeStruct{ .x = aFunc, }; //works
const my_other = SomeStruct{ .x = bFunc, }; //Compile error, expected type IFoo, got fn(f32)f32.
Since #1717 is accepted, I think it is safe to say that the open proposal #1595 supercedes this one.
Most helpful comment
Another alternative would be to make function definitions expressions (#1717) and use some variation of distinct types (#1595) to do something like this: