Struct embedding in Go is a powerful feature for composition, letting you reuse fields and methods from one struct inside another without explicit inheritance, since Go doesn’t have classes or traditional inheritance like Java. Let’s break it down.
Suppose you have a Person struct:
type Person struct {
Name string
Age int
}
func (p Person) Greet() {
fmt.Println("Hi, my name is", p.Name)
}
You can embed Person inside another struct, say Employee:
type Employee struct {
Person // <-- embedded struct
Position string
}
When you embed a struct:
Example:
func main() {
e := Employee{
Person: Person{Name: "Alice", Age: 30},
Position: "Engineer",
}
fmt.Println(e.Name) // Accessing embedded Person's Name
e.Greet() // Calling embedded Person's method
}
Output:
Alice
Hi, my name is Alice
Even though Employee doesn’t explicitly define Name or Greet(), it inherits them via embedding.