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.
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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?