Home >Backend Development >Golang >Why Do Different Field Orders in Go Structs Result in Varying Sizes?
Summary: Different implicit padding is added depending on the order of the fields in a struct, which affects its size.
Different architectures require different alignment for memory addresses. For example, in the code provided, it's assumed that the target architecture is 386, where the alignof int64 is 8 bytes.
In struct A, since the first field is bool, there is a 7-byte implicit padding after A.a to ensure that A.b, which is of type int64, starts on an 8-byte aligned address. This padding is necessary because the struct itself is aligned to 8 bytes.
In struct B, however, there is only a 3-byte implicit padding after B.a because it is followed by a field of type int (which has a size of 4 bytes) and not int64.
The specification for Go states that a struct or array type has size zero if it contains no fields or elements that have a size greater than zero.
This means that distinct zero-size variables may have the same address in memory. Current implementations follow this rule, so no memory is allocated for values of types having a size of zero, including the empty struct struct{} and arrays of zero length.
For example, in the code provided, C is a zero-size struct. As a result, no memory is allocated for instances of C.
The above is the detailed content of Why Do Different Field Orders in Go Structs Result in Varying Sizes?. For more information, please follow other related articles on the PHP Chinese website!