What is Struct Embedding in Go: Simple Explanation and Example
struct embedding means placing one struct type inside another without a field name, allowing the outer struct to use the inner struct's fields and methods directly. It is a way to achieve composition and reuse code without traditional inheritance.How It Works
Struct embedding in Go works like putting one box inside another without labeling it. Imagine you have a toolbox (outer struct) and you put a smaller box (inner struct) inside it without a tag. You can then use the tools inside the smaller box as if they were directly in the big toolbox.
This means the outer struct automatically gets access to all the fields and methods of the embedded struct. It helps to share common features between different structs without repeating code. Unlike inheritance in other languages, embedding is simpler and more flexible because it is just a field without a name.
Example
This example shows a Person struct embedded inside an Employee struct. The Employee can use Person's fields directly.
package main import "fmt" type Person struct { Name string Age int } func (p Person) Greet() { fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.Name, p.Age) } type Employee struct { Person // embedded struct Company string } func main() { e := Employee{ Person: Person{Name: "Alice", Age: 30}, Company: "Acme Corp", } e.Greet() // calls Person's method fmt.Println(e.Name) // accesses embedded field directly fmt.Println(e.Company) // accesses Employee's own field }
When to Use
Use struct embedding when you want to reuse fields and methods from one struct inside another without writing extra code. It is helpful for building complex types from simpler ones, like adding employee details to a person or adding features to a vehicle.
It is also useful when you want to share behavior but avoid the complexity of inheritance. For example, embedding a logger struct inside different components to give them logging ability.
Key Points
- Embedding is like including one struct inside another without a field name.
- The outer struct can access embedded struct's fields and methods directly.
- It helps with code reuse and composition instead of inheritance.
- Embedded structs can be used to add common behavior to multiple types.