Explain the use of Go's struct embedding for code reuse?

Go's struct embedding is a way to reuse code by embedding one struct within another. This allows the embedded struct's fields and methods to be accessed directly from the outer struct, as if they were part of the outer struct itself.

To embed a struct in Go, we include a field of the embedded struct's type within the outer struct, without specifying a field name. Here's an example:

type Person struct {
    Name string
    Age int

type Employee struct {
    Salary int

In this example, we have defined a **Person** struct with two fields, **Name** and **Age**. We then define an **Employee** struct that embeds the **Person** struct, and adds a **Salary** field.

Now, we can create an **Employee** value and access the fields of both the **Employee** and **Person** structs:

func main() {
    emp := Employee{Person{"Alice", 30}, 5000}
    fmt.Println(emp.Name)   // prints "Alice"
    fmt.Println(emp.Age)    // prints 30
    fmt.Println(emp.Salary) // prints 5000

In this example, we have created an **Employee** value **emp** that includes a **Person** value with **Name** "Alice" and **Age** 30, and a **Salary** of 5000. We can access the fields of the embedded **Person** struct directly from the **emp** value.

Struct embedding can be a powerful technique for code reuse, as it allows us to build complex structs by composing simpler ones. We can also use struct embedding to implement interface inheritance, by embedding a struct that implements an interface within another struct that also implements the same interface.

In summary, Go's struct embedding allows us to reuse code by embedding one struct within another. This can be a powerful technique for building complex structs and implementing interface inheritance.

Related Questions You Might Be Interested