Embedding Primitive Types in Go: A Closer Look
When constructing custom types, you may encounter the concept of embedding primitive types such as int32. While this technique is commonly used to embed structs or interfaces, embedding primitive types raises certain questions.
Can Embedding int32 Be Useful?
No, directly embedding int32 doesn't provide any immediate benefits over using a regular field. int32 is a primitive type with no associated methods or fields.
Does int32 Have Methods Accessible to User Instances?
No, int32 has no methods. You can verify this using the reflect package:
fmt.Println(reflect.TypeOf(int32(0)).NumMethod()) // Prints 0
Accessing Embedded Primitive Type Values
To access the embedded int32 value in the User struct, you can use the unqualified type name as the field name:
type User struct { int32 Name string } u := User{3, "Bob"} fmt.Println(u.int32) // Prints 3
Advantages and Disadvantages of Embedding Primitive Types
While embedding primitive types may not provide direct advantages, it can have disadvantages:
Therefore, it's generally not recommended to embed primitive types unless there's a specific reason for doing so, such as implementing interfaces that require access to the embedded value.
The above is the detailed content of Should You Embed Primitive Types Like int32 in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!