Struct embedding
Context
Section titled “Context”Go supports composition via struct embedding (similar to mixins). An embedded struct’s fields and methods are promoted to the outer struct.
Example
Section titled “Example”Embed a Person struct inside an Employee.
Code example
Section titled “Code example”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)}Output
Section titled “Output”Alice 30 123 Engineering