Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic function to get size of any structure in golang

I am writing a generic function to get the size of any type of structure, similar to sizeof function in C.

I am trying to do this using interfaces and reflection but I'm not able to get the correct result. Code is below:

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    type myType struct {
        a int
        b int64
        c float32
        d float64
        e float64
    }
    info := myType{1, 2, 3.0, 4.0, 5.0}
    getSize(info)
}

func getSize(T interface{}) {
    v := reflect.ValueOf(T)
    const size = unsafe.Sizeof(v)
    fmt.Println(size)
}

This code returns wrong result as 12. I am very new to Go, kindly help me on this.

like image 653
sujin Avatar asked Jul 10 '15 10:07

sujin


1 Answers

You're getting the size of the reflect.Value struct, not of the object contained in the interface T. Fortunately, reflect.Type has a Size() method:

size := reflect.TypeOf(T).Size()

This gives me 40, which makes sense because of padding.

like image 191
Thomas Avatar answered Sep 19 '22 21:09

Thomas