In Go, you cannot embed an interface directly into a struct like you can with structs. However, you can achieve similar functionality using anonymous fields.
Here's an example to demonstrate how to embed an interface into a struct:
package main
import "fmt"
// Define an interface
type Printer interface {
Print(message string)
}
// Define a struct that "implements" the Printer interface
type HelloPrinter struct{}
func (hp HelloPrinter) Print(message string) {
fmt.Println("Hello", message)
}
// Define a struct that embeds the Printer interface
type MyStruct struct {
Printer // Anonymous field of type Printer interface
}
func main() {
// Create an instance of MyStruct
myStruct := MyStruct{}
// Assign a value that implements the Printer interface to the embedded field
myStruct.Printer = HelloPrinter{}
// Call the Print method on the embedded Printer interface
myStruct.Print("World")
}
In this example, MyStruct
embeds the Printer
interface as an anonymous field. By doing this, MyStruct
inherits the methods defined in the Printer
interface.
To use the embedded interface, you can simply assign a value that implements the interface to the embedded field. In the main
function, myStruct.Printer
is assigned an instance of the HelloPrinter
struct, and then the Print
method is called on myStruct
, which in turn calls the HelloPrinter
's Print
method.
Output:
Hello World
By utilizing anonymous fields and assigning values that implement the desired interface, you can effectively achieve embedding an interface into a struct in Go.