Junior — Middle
How are interfaces defined and used in the Go language?
sobes.tech AI
Answer from AI
In Go, interfaces are defined as a set of methods that a type must implement to be considered satisfying that interface. The interface definition looks like this:
// Interface definition
type Reader interface {
Read(p []byte) (n int, err error)
}
A type automatically implements an interface if it has all the methods specified in the interface. There is no need to explicitly declare implementation.
Example usage:
type File struct {}
func (f File) Read(p []byte) (n int, err error) {
// read implementation
return 0, nil
}
func process(r Reader) {
buf := make([]byte, 100)
r.Read(buf)
}
func main() {
var f File
process(f) // File implements Reader
}
Thus, interfaces in Go allow writing flexible and extensible code, relying on the behavior of types rather than their specific implementations.