Home >Backend Development >Golang >How Can I Generically Get the Size of Any Data Structure in Go?
Generic Function to Obtain Structure Size in Go
This question addresses the creation of a generic function that determines the size of any data structure in Go, analogous to C's sizeof function. The developer attempted to accomplish this using interfaces and reflection but encountered incorrect results.
Understanding the Issue
The provided code calculates the size of the reflect.Value struct rather than the object stored within the T interface. This is caused by the use of reflect.ValueOf(T). To resolve this, it is necessary to determine the size of the type, not the value, using reflect.TypeOf(T).Size().
Corrected Code:
func getSize(T interface{}) { v := reflect.ValueOf(T) size := reflect.TypeOf(v).Size() fmt.Println(size) }
Revised Output:
With this correction, the code returns the expected size of 40 for the given structure, accounting for padding.
The above is the detailed content of How Can I Generically Get the Size of Any Data Structure in Go?. For more information, please follow other related articles on the PHP Chinese website!