What is struct embedding in Go? Named and unnamed embedding.
sobes.tech AI
Answer from AI
Embedding structures in Go is a mechanism that allows including one structure into another without explicitly specifying a field, providing a form of inheritance and composition.
Named embedding — when the structure's field has a name and type, for example:
type Address struct {
City, State string
}
type Person struct {
Addr Address // named embedding
Name string
}
Access to fields in this case is through the field name: p.Addr.City.
Unnamed (anonymous) embedding — when only the type is specified in the structure, without a field name:
type Address struct {
City, State string
}
type Person struct {
Address // unnamed embedding
Name string
}
In this case, the fields of the embedded structure are "embedded" into the parent structure, and can be accessed directly: p.City.
This allows implementing composition and code reuse, as well as imitating inheritance, since methods of the embedded structure become methods of the parent structure.