In Go, embedding is a language feature used to create reusable code and reduce duplication by embedding one struct type into another. When a struct type is embedded, its fields and methods become part of the embedding struct without explicitly declaring them. Here's how you can use embedding effectively in Go:
type CommonFunc struct {
// common fields
Field1 string
Field2 int
}
func (c *CommonFunc) Method1() {
// common method implementation
}
// Add more common methods as needed
type Struct1 struct {
CommonFunc // Embed the CommonFunc struct type
// struct-specific fields
Field3 float64
}
type Struct2 struct {
CommonFunc // Embed the CommonFunc struct type
// struct-specific fields
Field4 bool
}
struct1 := Struct1{}
struct1.Field1 = "Value"
struct1.Method1() // Call the common method
struct2 := Struct2{}
struct2.Field2 = 10
struct2.Method1() // Call the common method
By using embedding, you can reuse the common functionality defined in CommonFunc
across multiple struct types (Struct1
and Struct2
) without manually duplicating the fields and methods in each struct.
Remember that if there are fields or methods with the same name in both the embedded struct and the embedding struct, the embedding struct's fields and methods override the embedded ones. You can access the embedded fields and methods explicitly using the embedded struct's type as well.