Home >Backend Development >Golang >Why Do Go Structs with the Same Fields Have Different Sizes?
The code provided demonstrates an intriguing behavior:
<br>type A struct {</p> <pre class="brush:php;toolbar:false">a bool b int64 c int
}
type B struct {
b int64 a bool c int
}
When printing the sizes of A{} and B{} using unsafe.Sizeof, we obtain surprising results:
<br>fmt.Println(unsafe.Sizeof(A{})) // Output: 24<br>fmt.Println(unsafe.Sizeof(B{})) // Output: 16<br>
Why do these structs have different sizes despite having the same fields?
The answer lies in field alignment. In Go, addresses of variables must be aligned based on their type, and this alignment is especially important for types like int64 (8-byte alignment). In the case of A, the first field a is a bool, which requires only 1 byte of storage. After this field, there is a 7-byte implicit padding to align the next field b (of type int64) on an 8-byte boundary. However, in the case of B, since the first field b is already aligned on an 8-byte boundary, there is no need for any implicit padding, resulting in a smaller struct size of 16 bytes.
Moving on, we encounter another interesting case:
<br>type C struct {<br>}<br>
When printing unsafe.Sizeof(C{}), we unexpectedly get an output of 0. How is this possible, given that every struct occupies some memory?
The Go specification states that a struct or array with no fields or elements with a size greater than zero has a size of zero. It also implies that two distinct zero-size variables may share the same memory address. This is the case with C{}, which has a size of zero and may not occupy any actual memory. Instead, it can reference the same memory address as other zero-size values, such as struct{}{}, []int{}, or even the empty array [3]struct{}{}.
Understanding field alignment and the concept of zero-size values enhances our comprehension of Go's memory management. By arranging fields strategically within a struct, we can optimize memory allocation and ensure efficient data manipulation.
The above is the detailed content of Why Do Go Structs with the Same Fields Have Different Sizes?. For more information, please follow other related articles on the PHP Chinese website!