Senior
Can a struct in Go implement multiple interfaces at once?
sobes.tech AI
Answer from AI
Yes, in Go a struct can implement multiple interfaces at once. In Go, interface implementation is implicit: if a struct contains all the methods of an interface, it is considered to implement that interface.
This means that if a struct implements methods for multiple interfaces, it automatically implements all of those interfaces simultaneously.
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 (m *MyStruct) Read() string {
return m.data
}
func (m *MyStruct) Write(s string) {
m.data = s
}
func main() {
var rw ReadWriter = &MyStruct{}
rw.Write("Hello")
fmt.Println(rw.Read()) // Output: Hello
}
Here, MyStruct implements the Reader and Writer interfaces, and therefore also the ReadWriter interface.