How do I embed structs and understand field promotion in Go?

In Go, embedding structs allows you to compose types by including one struct within another, promoting the fields and methods of the embedded struct to the enclosing struct. This feature is useful for code reuse, organization, and logical grouping of related behaviors.

Field promotion means that you can access the fields of the embedded struct as if they were fields of the enclosing struct, thereby simplifying the interface of the enclosing struct.

Example of Struct Embedding

type Address struct { City string Country string } type Person struct { Name string Age int Address // Embedding Address struct } func main() { p := Person{ Name: "John Doe", Age: 30, Address: Address{ City: "New York", Country: "USA", }, } // Accessing fields using embedded struct fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age) fmt.Println("City:", p.City) // Promoted field fmt.Println("Country:", p.Country) // Promoted field }

Go Struct Embedding Field Promotion Go Structs Go Programming