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|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?