Home >Backend Development >Golang >Do Embedded Primitive Types in Go Offer Any Real Advantages?
Embedded Types: Exploring the Usefulness of Primitive Embeddings
When working with Go structs, the concept of embedding primitive types can arise. Consider the code snippet below:
type User struct { int32 Name string }
This code defines a User struct that embeds the int32 primitive type. However, questions arise regarding the utility of such an embedding:
Do Embedded Primitives Have Methods?
No, embedded primitives like int32 do not have any methods associated with them. To verify this, one can use reflection to inspect the number of methods available:
fmt.Println(reflect.TypeOf(int32(0)).NumMethod())
The output will be 0, indicating that int32 has no methods.
Accessing Embedded Primitive Values
To access the embedded int32 value within a User instance, one can directly use the unqualified type name as the field name:
u := User{3, "Bob"} fmt.Printf("%#v\n", u) u.int32 = 4 fmt.Println(u.int32)
Output:
main.User{int32:3, Name:"Bob"} 4
Advantages of Embedding
While embedding primitive types might not provide direct access to methods, it does offer certain advantages when dealing with interfaces and method overriding.
Disadvantages of Embedding Predeclared Types
When embedding predeclared types like int32, there is a disadvantage to consider:
The above is the detailed content of Do Embedded Primitive Types in Go Offer Any Real Advantages?. For more information, please follow other related articles on the PHP Chinese website!