In Go, we can embed multiple interfaces and structs into a single struct using the concept of struct composition. This allows us to create a new struct that contains the fields and methods of other structs or interfaces. Here's an example:
package main
import "fmt"
// Interface 1
type Animal interface {
Sound()
}
// Struct 1
type Dog struct{}
func (d Dog) Sound() {
fmt.Println("Woof!")
}
// Struct 2
type Cat struct{}
// Interface 2
type Runner interface {
Run()
}
func (c Cat) Sound() {
fmt.Println("Meow!")
}
func (c Cat) Run() {
fmt.Println("Cat is running!")
}
// Struct that embeds both the Animal and Runner interfaces
type AnimalRunner struct {
Animal
Runner
}
func main() {
// Creating an instance of AnimalRunner struct
ar := AnimalRunner{
Animal: Dog{},
Runner: Cat{},
}
ar.Sound() // Calling the Sound method from the Animal interface
ar.Run() // Calling the Run method from the Runner interface
}
In the above example, we have two interfaces Animal
and Runner
, and two corresponding structs Dog
and Cat
. The AnimalRunner
struct embeds both the Animal
and Runner
interfaces using the field names as the type names.
We can then create an instance of the AnimalRunner
struct and assign values of Dog{}
and Cat{}
to the embedded fields Animal
and Runner
respectively. This allows us to access and use methods defined in both Animal
and Runner
interfaces.
Running the above code will produce the following output:
Woof!
Cat is running!
Note that when embedding interfaces and structs, if there are overlapping method names or field names, it is necessary to explicitly provide a method or field name when accessing them to avoid ambiguity.