Home  >  Article  >  Backend Development  >  How Can I Generically Determine the Size of Any Go Structure?

How Can I Generically Determine the Size of Any Go Structure?

DDD
DDDOriginal
2024-11-26 07:58:08801browse

How Can I Generically Determine the Size of Any Go Structure?

How to Create a Generic Function to Determine the Size of Any Structure in Go

One of the commonly performed tasks in programming is determining the size of a structure. In Go, this can be achieved using the unsafe.Sizeof function. However, creating a generic function that can handle any type of structure is a bit more challenging.

Issue

A common approach to creating a generic function is to use interfaces and reflection. However, using this approach as shown below yields incorrect results:

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    type myType struct {
        a int
        b int64
        c float32
        d float64
        e float64
    }
    info := myType{1, 2, 3.0, 4.0, 5.0}
    getSize(info)
}

func getSize(T interface{}) {
    v := reflect.ValueOf(T)
    const size = unsafe.Sizeof(v)
    fmt.Println(size)
}

This code returns an incorrect result of 12, as it determines the size of the reflect.Value struct instead of the actual structure stored in the interface.

Solution

To resolve this issue, use the reflect.Type instead of reflect.Value to obtain the size information. The reflect.Type type has a Size() method that returns the size of the corresponding type:

size := reflect.TypeOf(T).Size()

Using this approach, the code provides the correct result of 40, accounting for padding within the structure.

The above is the detailed content of How Can I Generically Determine the Size of Any Go Structure?. 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