Zig's (.{}){} syntax

submited by
Style Pass
2024-11-05 12:30:03

While we can reason that we're creating an allocator, the (.{}){} syntax can seem a bit much. This is a combination of three separate language features: generics, anonymous struct literals and default field values.

One of Zig's more compelling feature is its advance compile-time (aka comptime) capabilities. This is the ability to have a subset of Zig run at compile-time. Comptime can be used for a number of different things, but the most immediately useful is to implement generic type. To create a generic type, we write a a function which returns a type. For example, if we wanted to create a linked list node, we'd do:

But this is redundant, because, in Zig, types always have to be known at compile time. Now consider these two equivalent ways to create a Node(T):

Thinking of Node(i32) as a type can take a bit of getting used to, but once you accept that it's no different than any other struct, the 2nd initialization hopefully makes sense.

Leave a Comment