通用函数来获取golang中任何结构的大小 [英] generic function to get size of any structure in golang

查看:85
本文介绍了通用函数来获取golang中任何结构的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个通用函数,该函数可以获取任何类型的结构并返回该结构的大小,类似于C语言中的 sizeof 函数.

I am writing a generic function which get any type of structure and return size of that structure, similar to sizeof function in C language.

我正在尝试使用界面和反射来执行此操作,但是我无法获得正确的结果.代码在下面

I am trying to do this using interface and reflection but i not able to get the correct result. Code is below

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)
}

此代码返回错误的结果12.我对golang很陌生,请帮忙解决这个问题.

This code return wrong result as 12. I am very new to golang, kindly help me on this.

推荐答案

您将获得 reflect.Value 结构的大小,而不是接口 T <中包含的对象的大小/code>.幸运的是, reflect.Type 具有一个 Size()方法:

You're getting the size of the reflect.Value struct, not of the object contained in the interface T. Fortunately, reflect.Type has a Size() method:

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

这给了我40,这是有填充意义的.

This gives me 40, which makes sense because of padding.

这篇关于通用函数来获取golang中任何结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆