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?

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?