You aspire to create a generic function in Go that mimics C's sizeof functionality, allowing you to determine the size of any data structure.
In your code, you attempted to utilize interfaces and reflection to achieve this. However, you encountered an issue where the returned size was incorrect.
The reason for this discrepancy lies in the fact that the code retrieved the size of the reflect.Value struct rather than the actual object encapsulated within the interface.
Fortunately, there's a straightforward solution to this problem. The reflect.Type type includes a Size() method that provides the size of the underlying type. By employing this method, you can obtain the size of the data structure itself:
size := reflect.TypeOf(T).Size()
In your specific case, this modification yields the correct size of 40 bytes, which incorporates padding.
The above is the detailed content of How Can I Get the Correct Size of a Generic Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!