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.


1️⃣ Basic concept

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
}

2️⃣ How it works

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.


3️⃣ Why use struct embedding?

  1. Code reuse: Share fields and methods without duplicating them.