Home >Backend Development >Golang >Why Do Structs with Identical Fields but Different Orders Have Different Sizes in Go?
In the provided code, two structs, A and B, with identical fields but different field orders, demonstrate differing sizes. Here's why:
Memory alignment requirements for data types dictate that addresses of fields must be multiples of specific values. For int64 fields, this multiple is 8 bytes.
In struct A, the first field is a bool, which takes 1 byte. To align the subsequent int64 field on an 8-byte boundary, 7 bytes of implicit padding are added after a.
In struct B, the first field is b of type int64. Since it's already aligned, only 3 bytes of implicit padding are needed after a to align the following int field, which takes 4 bytes.
Due to this implicit padding, the size of A is 24 bytes (1 byte for a, 8 bytes for b, and 15 bytes of padding). Meanwhile, B is 16 bytes (1 byte for a, 3 bytes of padding, 8 bytes for b, and 4 bytes for c).
Struct C is declared entirely empty, resulting in a size of 0 bytes. According to the Go language specification, structures with no fields larger than zero have a size of zero.
For zero-size values, the language allows for the same memory address to be reused for distinct variables. This means that for a := C{}, no memory is actually allocated by the system.
The above is the detailed content of Why Do Structs with Identical Fields but Different Orders Have Different Sizes in Go?. For more information, please follow other related articles on the PHP Chinese website!