The reference says:
Unlike normal structs,
packed structs have guaranteed in-memory layout:
- Fields remain in the order declared, least to most significant.
- Non-ABI-aligned fields are packed into the smallest possible ABI-aligned integers in accordance with the target endianness.
I am having trouble parsing the meaning of the last one — all the words individually make sense to me, but the overall idea eludes me. Could someone give a couple of examples of what’s happening there?
I’m having the exact same reaction as you. Let me explore the change that led to that wording…
OK I figured it out from
git blame. It is a sentence that I added a long time ago when the compiler was written in C++ and packed structs worked completely differently. So, that sentence should simply be deleted.
Any other clarifications to this section while I’m at it?
Nearby thing caught my eye (about extern structs)
This kind of struct should only be used for compatibility with the C ABI. Every other use case should be solved with packed struct or normal struct.
When we were upgrading to 0.11
We changed a bunch of packed structs to extern structs, because we need defined memory layout, not an integer in a fancy hat.
Release changelog also shows example of using extern to control padding, so perhaps reference is a bit outdated?
In the near future, the syntax will change to avoid confusion with C’s packed structs, which is a different concept that relates to padding. In Zig, such a struct is done by using
extern and setting each field’s alignment to 1 byte: