3 ms·
> C99 designated init is still superior to what Zig has to offer for struct initialization Can you explain this for the ignorant?
by triyambakam 3y ago
> C99 designated init is still superior to what Zig has to offer for struct initialization
Can you explain this for the ignorant?
- flohofwoe 3y agoWhen initializing a struct, Zig currently doesn't allow chained designators and also doesn't allow to partially initialize arrays and have the rest of the array filled up with default values (the first one isn't all that important, but the second is). E.g. the closest Zig equivalent to this C99 code: https://github.com/floooh/sokol-samples/blob/b3bc55c4411fa03770e2ff4303e1d49f9f36616d/sapp/texcube-sapp.c#L120-L136 https://github.com/floooh/sokol-samples/blob/b3bc55c4411fa03... ...is this: https://github.com/floooh/sokol-zig/blob/a4b3c287fadd153a5046f6fd4b35f4118b25fe53/src/examples/texcube.zig#L106-L118 https://github.com/floooh/sokol-zig/blob/a4b3c287fadd153a504... ...note how part of the initialization had to be moved out into separate assignments, which means the struct can't be created as const. There's a ticket about this here, but it's currently not high-priority: https://github.com/ziglang/zig/issues/6068 https://github.com/ziglang/zig/issues/6068 Zig also isn't alone in this, I haven't encountered any other programming language yet which has such a flexible struct initialization syntax as C99. Odin is probably the closest I've seen yet. https://github.com/floooh/sokol-odin/blob/084c2429bd52b8d9dc852f77947cd248b106718f/examples/texcube/main.odin#L115-L130 https://github.com/floooh/sokol-odin/blob/084c2429bd52b8d9dc...
- anonymoushn 3y agoFor that specific case, it seems like the array should be a packed struct (whatever needs it to be an array can receive an array via @bitcast). These features of C designated initialization seem great though.
- flohofwoe 3y agoThere's also another solution to use slices instead of 'embedded arrays', but with slices you suddenly need to think about ownership (e.g. what happens with the referenced slices when the top-level struct is copied).
- anonymoushn 3y agoI agree that it's worth avoiding slice members for this reason if the slices are the only thing that would stop memcpy'd copies of the struct from "just working."