Home >Backend Development >Golang >How Can I Get the Size of Any Structure in Go Using Reflection?

How Can I Get the Size of Any Structure in Go Using Reflection?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 01:40:14528browse

How Can I Get the Size of Any Structure in Go Using Reflection?

Generic Function to Get Size of Any Structure in Go

Problem:
The goal is to create a generic function in Go that can determine the size of any arbitrary structure, similar to the sizeof function in C.

Code and Error:
The provided code employs reflection to retrieve the structure's size. However, reflecting on the reflect.Value struct, rather than reflecting on the object, yields an incorrect result. Here's the code in question:

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) // Prints 12, which is incorrect
}

Solution:
To resolve this issue, one needs to reflect on the type rather than the value of the object. The reflect.Type has a Size() method that provides the correct size. Here's the updated code:

package main

import (
    "fmt"
    "reflect"
)

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)
    size := v.Type().Size()
    fmt.Println(size) // Prints 40, which is correct
}

Explanation:
The corrected code uses the Size() method of reflect.Type, which returns the size of the structure without overhead from reflection.

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