Home >Backend Development >Golang >Do Embedded Primitive Types in Go Offer Any Real Advantages?

Do Embedded Primitive Types in Go Offer Any Real Advantages?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 01:36:31199browse

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.

  • Promoted methods from the embedded type can streamline interface implementations.
  • Methods can be overridden in the embedding type, allowing for customized behavior when interacting with values of that type.
  • Embedded fields are promoted, shortening references to those fields.

Disadvantages of Embedding Predeclared Types

When embedding predeclared types like int32, there is a disadvantage to consider:

  • Embedded predeclared types that start with lowercase letters are automatically unexported, limiting their accessibility.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn