Whatever happened to 'functions as expressions'?

I’ve had the use for this thing exactly, and had to get some help here.
In summary, I needed to deserialize unions a bit differently than the std.json module does it, and I needed it to be the same across multiple unions. The solution was to write a function that returns a function that I could then assign to the jsonParse* methods.

Afaict it needed to be a second-order function because while the structure of each function is the same it needed to know the names of the union fields to deserialize the json object correctly. There might be better ways to do this but it’s the best way I could think of.

Regarding the mental model and where the function object lives, I think for functions that do not create a closure it’s simplest to just think of it as a namespaced function that lives in the text part of the object file (or the corresponding part of a windows executable). For a function that closes over (is that how you say it?) the outer scope I cannot say for sure, I don’t know how zig currently implements closures. I think someone earlier in this thread or the linked github issue mentioned that structs can only use comptime-known variables, so keeping that restriction would make sense here too.

1 Like