Home > Backend Development > Golang > How Can I Programmatically Determine the Size of a Go Struct?

How Can I Programmatically Determine the Size of a Go Struct?

Linda Hamilton
Release: 2024-12-18 13:22:25
Original
961 people have browsed it

How Can I Programmatically Determine the Size of a Go Struct?

Obtaining the Size of Go Structs Programmatically

Calculating the size of a Go struct involves understanding the underlying types and the alignment requirements.

Unsafe Package Method

The Sizeof method from the unsafe package returns the size of a variable or struct. However, it's important to note that this size does not include memory referenced by the variable.

import "unsafe"

func GetStructSize(s interface{}) int {
    return int(unsafe.Sizeof(s))
}
Copy after login

Calculating Struct Size Manually

The size of a struct depends on the types of its fields and the order in which they appear. Here are some guidelines:

  • Primitive types: 1 byte (bool, int8, uint8), 2 bytes (int16, uint16), 4 bytes (int32, uint32, float32), 8 bytes (int64, uint64, float64, pointer).
  • string: 16 bytes (two 8-byte alignments)
  • slice: 24 bytes (three 8-byte alignments)
  • array: n * size of its element type
  • Fields are aligned to their size. If a field's size is not divisible by its alignment, padding is added.

For example:

type Coord3d struct {
    X, Y, Z int64
}

// Size of Coord3d is 24 bytes (3 * 8 bytes)
Copy after login

Verifying Size with an Online Service

You can also verify your calculated size using an online service like [Go Playground](https://play.golang.org/):

func main() {
    type Coord3d struct {
        X, Y, Z int64
    }
    
    fmt.Println(unsafe.Sizeof(Coord3d{})) // Outputs: 24
}
Copy after login

The above is the detailed content of How Can I Programmatically Determine the Size of a Go Struct?. 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