Generic Function for Determining Data Structure Size in Go
In Go, the lack of a native function similar to C's sizeof operator poses a challenge when retrieving the size of arbitrary data structures. To overcome this, leveraging interfaces and reflection offers a solution.
The provided code attempts to achieve this using:
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) // Incorrectly produces 12 }
However, this approach yields an incorrect result as it calculates the size of the reflect.Value structure rather than the object stored in the interface T.
The solution lies in utilizing the Size() method of the reflect.Type:
size := reflect.TypeOf(T).Size() // Corrects the size calculation
This modification enables the function to accurately determine the size of the input data structure, accounting for padding. In the example given, it correctly reports the size as 40.
The above is the detailed content of How Can I Get the Size of Any Data Structure in Go?. For more information, please follow other related articles on the PHP Chinese website!