Skip to content

Struct embedding

Go supports composition via struct embedding (similar to mixins). An embedded struct’s fields and methods are promoted to the outer struct.

Embed a Person struct inside an Employee.

package main
import "fmt"
type Person struct {
Name string
Age int
}
type Employee struct {
Person // embedded
ID int
Department string
}
func main() {
e := Employee{
Person: Person{Name: "Alice", Age: 30},
ID: 123,
Department: "Engineering",
}
// Access promoted fields directly
fmt.Println(e.Name, e.Age, e.ID, e.Department)
}
Terminal window
Alice 30 123 Engineering