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

DDD
Release: 2024-11-26 07:58:08
Original
801 people have browsed it

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)
}
Copy after login

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()
Copy after login

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!

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