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 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度