Senior
What are interfaces in Go? How do types implement interfaces?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that describe behavior. A type implements an interface if it contains all the methods declared in the interface, without explicitly declaring that it implements the interface.
This is called implicit interface implementation. It allows for writing more flexible and extensible code.
Example:
package main
import "fmt"
type Reader interface {
Read(p []byte) (n int, err error)
}
type File struct {}
func (f File) Read(p []byte) (n int, err error) {
// implementation of read
return 0, nil
}
func main() {
var r Reader
f := File{}
r = f // File implements Reader
fmt.Println(r)
}
Here, the type File implements the Reader interface because it has a Read method with the required signature.