generic function to get size of any structure in Go

Issue

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.

Solution

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.

Answered By – Thomas

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.