What is the difference between Go's struct embedding and composition for structs in Go?
In Go, both struct embedding and composition are ways to compose a new struct from existing structs.
Struct embedding is a way to include an existing struct as a field in a new struct. This allows the new struct to inherit the fields and methods of the embedded struct, and to use them as if they were its own. The syntax for struct embedding is to include the name of the embedded struct as a field type, without a field name. For example:
type Person struct {
name string
age int
}
type Employee struct {
Person
salary float64
}
In this example, the **Employee**
struct embeds the **Person**
struct, which means that an **Employee**
value will have all of the fields and methods of the **Person**
struct, as well as its own **salary**
field.
Struct composition, on the other hand, is a way to create a new struct by combining multiple existing structs, without any of them being embedded as a field. This means that the new struct does not inherit any fields or methods from the existing structs. Instead, it has its own set of fields and methods that are defined explicitly. The syntax for struct composition is to include the names of the existing structs as field types, with field names. For example:
type Person struct {
name string
age int
}
type Address struct {
street string
city string
}
type ContactInfo struct {
email string
phone string
}
type Customer struct {
person Person
address Address
contact_info ContactInfo
}
In this example, the **Customer**
struct is composed of the **Person**
, **Address**
, and **ContactInfo**
structs, which means that it has its own fields and methods, and does not inherit anything from the existing structs.