Home >Backend Development >Golang >Should I Embed Primitive Types in Go Structs?
Go: Embedding Primitive Types
Embedding involves the inclusion of one type within another. This can be useful in a variety of scenarios. However, when it comes to embedding primitive types like int32, certain considerations apply.
Methods of Primitive Types
Firstly, primitive types do not possess any methods. This means that embedding int32 in a struct, as in the example you provided, does not grant the User struct access to any int32 methods. To confirm this, you can perform a reflection check using reflect.TypeOf(int32(0)).NumMethod(). This will return 0, indicating the absence of methods.
Accessing Embedded Values
You can access the value of the embedded int32 field using the unqualified type name as the field name. For instance, if you have a User instance named u, you can access the embedded int32 value with u.int32.
Advantages of Embedding Primitive Types
There are no substantial advantages to embedding primitive types, as they do not possess any methods or fields.
Disadvantages of Embedding Primitive Types
Conversely, embedding primitive types can introduce disadvantages. By default, embedded predeclared types (those starting with lowercase letters) are unexported, meaning they can only be referenced within the declaring package. This limits their usefulness and flexibility.
Therefore, it is generally not recommended to embed primitive types unless a specific advantage can be gained, such as method promotion or field overriding.
The above is the detailed content of Should I Embed Primitive Types in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!