Home >Backend Development >Golang >How Big is My Go Struct, Really?

How Big is My Go Struct, Really?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 19:50:10848browse

How Big is My Go Struct, Really?

Determining the Size of a Go Struct

In Go, the unsafe.Sizeof() method can be utilized to programmatically determine the size occupied by a struct. However, it's important to note that this method only reports the size of the struct descriptor, excluding any referenced memory.

To delve deeper, there are straightforward rules that govern the size of a struct:

  • The alignment of a struct is determined by its largest primitive field.
  • Fields within the struct are aligned to their own alignment requirements.
  • This alignment may result in padding between fields to meet the alignment constraints.
  • Strings occupy 16 bytes (2 alignments of 8 bytes).
  • Slices occupy 24 bytes (3 alignments of 8 bytes).

Based on these rules, one can estimate the size of a struct manually. However, an online tool can be leveraged to verify the estimation, ensuring accuracy. By following these guidelines and understanding the underlying alignment principles, you can accurately determine the size of any Go struct.

The above is the detailed content of How Big is My Go Struct, Really?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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