To implement methods of an embedded interface in a struct in Go, you simply need to embed the interface within the struct, and then provide the method implementations for the embedded interface within the struct itself.
Here's an example:
package main
import "fmt"
type Reader interface {
Read() string
}
type Writer interface {
Write(string)
}
type ReadWriter interface {
Reader
Writer
}
type MyStruct struct {
data string
}
func (s *MyStruct) Read() string {
return s.data
}
func (s *MyStruct) Write(data string) {
s.data = data
}
func main() {
myStruct := MyStruct{data: "Hello World"}
var rw ReadWriter
rw = &myStruct
rw.Write("Goodbye World")
fmt.Println(rw.Read())
}
In this example, Reader
and Writer
are individual interfaces, and ReadWriter
is an embedded interface that embeds both Reader
and Writer
. The MyStruct
struct embeds the ReadWriter
interface.
To implement the methods of the embedded interface ReadWriter
, you implement the Read()
and Write()
methods for the MyStruct
struct. The Read
method reads the data from the struct, while the Write
method writes new data to the struct.
In the main
function, we create an instance of MyStruct
and assign it to the ReadWriter
interface rw
. We can then call the Write()
method and the Read()
method on rw
, which will use the implementations provided in the MyStruct
struct.