Home > Backend Development > Golang > Why Do Go Structs Have Different Sizes Depending on Field Order?

Why Do Go Structs Have Different Sizes Depending on Field Order?

DDD
Release: 2024-12-08 14:20:15
Original
906 people have browsed it

Why Do Go Structs Have Different Sizes Depending on Field Order?

Struct Size Discrepancy with Field Reordering

In Go, structs can exhibit different sizes when their fields are arranged in different orders.

Issue 1: Erroneous Struct Sizes

type A struct {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">a bool
b int64
c int
Copy after login

}

type B struct {

b int64
a bool
c int
Copy after login

}

When running unsafe.Sizeof(A{}), the result is 24 bytes, while unsafe.Sizeof(B{}) prints 16 bytes. Despite having the same set of fields, their differing order leads to this size variation.

Explanation: Implicit Padding

The sizes of structs are influenced by alignment constraints. int64 values require alignment on 8-byte addresses. In structure A, after the bool field (1 byte), 7 bytes of implicit padding are added to ensure alignment for the following int64 field (8 bytes). This explains the 24-byte size.

In structure B, however, only 3 bytes of padding are necessary after the bool field as the int field is only 4 bytes. Thus, the overall size becomes 16 bytes.

Issue 2: Zero-Sized Struct C

type C struct {<br>}<br>

The size of struct C is 0, as it has no fields with a size greater than zero. However, this does not necessarily imply that no memory is allocated for an instance of type C.

Explanation: Implementation Optimization

According to the Go specification, zero-size values may share memory addresses. While the spec suggests using the same address, it is not a requirement. Current Go implementations utilize this optimization to conserve memory for variables with a size of zero. Hence, despite C having a size of zero, the system may still allocate some memory for a variable of type C.

The above is the detailed content of Why Do Go Structs Have Different Sizes Depending on Field Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template