Explain the use of Go's embedded types for code reuse?
In Go, you can embed one struct within another struct to reuse its fields and methods. This is known as embedding or composition. The fields and methods of the embedded struct become part of the embedding struct, and they can be accessed using the dot notation.
Here is an example:
type Person struct {
name string
age int
}
type Employee struct {
Person
salary int
}
func (p *Person) greet() {
fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.name, p.age)
}
func main() {
emp := Employee{
Person: Person{name: "John", age: 30},
salary: 50000,
}
emp.greet() // Output: Hello, my name is John and I am 30 years old.
}
In this example, the **Employee**
struct embeds the **Person**
struct, which means that **Employee**
has access to all the fields and methods of **Person**
. In the **main**
function, we create a new **Employee**
object and initialize its **Person**
field with a **Person**
object. We can then call the **greet**
method of the **Person**
object using the **emp**
variable, which is an instance of **Employee**
.
Embedded types are a powerful feature of Go that can simplify code and increase reusability. However, care should be taken when using them to avoid creating complex, hard-to-understand code.