dongxian1921 2018-07-19 21:23
浏览 1074
已采纳

如何在Go中获取包含数据结构的结构的大小?

I'm currently trying to get the size of a complex struct in Go.

I've read solutions that use reflect and unsafe, but neither of these help with structs that contain arrays or maps (or any other field that's a pointer to an underlying data structure).

Example:

type testStruct struct {
    A     int
    B     string
    C     struct{}
    items map[string]string
}

How would I find out the correct byte size of the above if items contains a few values in it?

  • 写回答

1条回答 默认 最新

  • doushao8421 2018-07-19 22:13
    关注

    You can get very close to the amount of memory required by the structure and its content by using the package reflect. You need to iterate over the fields and obtain the size of each field. For example:

    func getSize(v interface{}) int {
        size := int(reflect.TypeOf(v).Size())
        switch reflect.TypeOf(v).Kind() {
        case reflect.Slice:
            s := reflect.ValueOf(v)
            for i := 0; i < s.Len(); i++ {
                size += getSize(s.Index(i).Interface())
            }
        case reflect.Map:
            s := reflect.ValueOf(v)
            keys := s.MapKeys()
            size += int(float64(len(keys)) * 10.79) // approximation from https://golang.org/src/runtime/hashmap.go
            for i := range(keys) {
                size += getSize(keys[i].Interface()) + getSize(s.MapIndex(keys[i]).Interface())
            }
        case reflect.String:
            size += reflect.ValueOf(v).Len()
        case reflect.Struct:
            s := reflect.ValueOf(v)
            for i := 0; i < s.NumField(); i++ {
                if s.Field(i).CanInterface() {
                    size += getSize(s.Field(i).Interface())
                }
            }
        }
        return size
    }
    

    This obtains the size of v using reflect and then, for the supported types in this example (slices, maps, strings, and structs), it computes the memory required by the content stored in them. You would need to add here other types that you need to support.

    There are a few details to work out:

    1. Private fields are not counted.
    2. For structs we are double-counting the basic types.

    For number two, you can filter them out before doing the recursive call when handling structs, you can check the kinds in the documentation for the reflect package.

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历