dongpu6141 2017-06-14 06:08
浏览 53
已采纳

在GAE / Go中获取结构的大小

I would like to get the size of a structure in GAE/Go.

I read this post and wrote the code as below.

import (
    "reflect"
    "unsafe"
)

func GetSize(T interface{}) {
    size := reflect.TypeOf(T).Size()
    return int((*int)(unsafe.Pointer(size)))
}

But this code does not work because GAE does not allow to import unsafe.

How can I do this in GAE/Go?

  • 写回答

1条回答 默认 最新

  • dsuxcxqep31023992 2017-06-14 11:24
    关注

    Your proposed solution is not valid code, it has multiple errors.

    For example GetSize() has no result type, so you couldn't return anything.

    Next, the expression you return is also a syntax error, it attempts to convert an *int pointer to int which is not valid.

    You need to dereference the pointer first, so the correct syntax would be:

    func GetSize(T interface{}) int {
        size := reflect.TypeOf(T).Size()
        return int(*(*int)(unsafe.Pointer(size)))
    }
    

    But. It makes no sense. reflect.Type.Size() already returns the size (the number of bytes needed to store a value of the given type), so there is no need of that unsafe magic. What may be confusing is that its return type is uintptr, but you may simply use that value after converting it to int for example.

    Simply use:

    func GetSize(v interface{}) int {
        return int(reflect.TypeOf(v).Size())
    }
    

    Testing it:

    fmt.Println("Size of int:", GetSize(int(0)))
    fmt.Println("Size of int64:", GetSize(int64(0)))
    fmt.Println("Size of [100]byte:", GetSize([100]byte{}))
    

    Output (try it on the Go Playground):

    Size of int: 4
    Size of int64: 8
    Size of [100]byte: 100
    

    One thing you must not forget: this GetSize() will not recurisvely examine the size of the passed value. So for example if it's a struct with a pointer field, it will not "count" the size of the pointed value, only the size of the pointer field.

    Constructing a GetSize() that recurisvely counts the total size of a complex data structure is non-trivial due to types like map. For details, see How to get variable memory size of variable in golang?

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

报告相同问题?

悬赏问题

  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败