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?