In Zig, what's a writer?
11 comments
·January 28, 2025schobers
It seems to me that the problem the author writes about is bigger than the writer abstraction. To me it feels like the lack of interfaces* and inheritance in the Zig language hinders creating meaningful abstractions because you always have to use composition.
Alternatively you could argue that this just isn't the right approach within the boundaries of the Zig language: don't try to abstract, just provide a meaningful implementation (in the standard library) and re-use (using composition).
Note:
*) Yes, I know, you can create interfaces but this introduces lots of boilerplate code where to cast/forward pointers to their correct type/implementation. For an example, the author refers to another article: https://www.openmymind.net/Zig-Interfaces/.
benob
How are you supposed to implement the concept of interface in non OOP languages?
unclad5968
The same way the OOP compilers implement them, with v-tables. Basically the compiler makes a table of function pointers so calls can be resolved (not sure resolved is the correct term) at runtime.
In Zig or any other C like language without "interfaces", you would implement the V-table by hand, which is a common idiom in Zig.
bsaul
do you have an example of what that would look like ?
I'm a bit confused about when you would construct this table and how one would use it
virexene
In Zig's case, you do what Rust/C++ do implicitly and create a table of function pointers
masklinn
Interface or interface-adjacent features are present in numerous non-OO languages: ML modules, Haskell typeclasses, rust traits, go interfaces, …
feverzsj
Using function pointers like most c projects do.
jimbob45
There’s no excuse for C not to have some syntactic sugar around function pointers at this point. They’re miserable to use.
ajb
It does. You don't need to use & on a function or * on a function pointer, this happens automatically (see https://stackoverflow.com/questions/7518815/function-pointer... ).
I suppose the : operator from lua would be useful.
GuestHNUser
Function pointers typically
I've been using zig for a week now. When I see a construct like writer I find myself looking for complexity that is just not there. I'm pleasantly surprised by the zig language design decisions. Initially I thought allocators were a pain but now I hardly notice them after I set up the struct init and deinit. And the myriad of zig pointer and slice types make me appreciate how C has overloaded the use of certain constructs in non-intuitive ways that we've just come to accept over the decades. I'm more impressed with zig than the last half dozen languages I've picked up - and the C/C++ interop at the language and compiler level is just the icing on the cake.