douquqiang1513 2015-07-10 10:32
浏览 84
已采纳

通用函数以获取golang中任何结构的大小

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

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

  • 写回答

1条回答 默认 最新

  • dongtaijiao7140 2015-07-10 10:40
    关注

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器