Home > Backend Development > Golang > Why Do Different Field Orders in Go Structs Result in Varying Sizes?

Why Do Different Field Orders in Go Structs Result in Varying Sizes?

Susan Sarandon
Release: 2024-12-05 01:36:10
Original
465 people have browsed it

Why Do Different Field Orders in Go Structs Result in Varying Sizes?

Struct has different size if the field order is different

1. Struct 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.

2. Zero size values

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template