How to use embedding to create reusable code and reduce duplication in Go?

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:

  1. Define the common functionality: Identify the common fields and methods that you want to reuse across multiple structs. Create a struct type for this common functionality.
type CommonFunc struct { // common fields Field1 string Field2 int } func (c *CommonFunc) Method1() { // common method implementation } // Add more common methods as needed
  1. Embed the common functionality: In the structs where you want to reuse the common functionality, embed the struct type created in the previous step.
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 }
  1. Access the embedded functionality: Now, the fields and methods of the embedded struct will be accessible directly from the embedding structs.
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.