Middle+
What is an interface in Go and how does duck typing work?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that describe behavior. Any type that implements all the methods of an interface is automatically considered its implementation, without explicitly declaring it in the code.
This implements the concept of duck typing: if an object "looks like a duck and quacks like a duck," then it is a duck. In Go, this means you don't need to explicitly declare that a type implements an interface — it's enough to have the necessary methods.
Example:
type Reader interface {
Read(p []byte) (n int, err error)
}
// Any type that has a method Read([]byte) (int, error) implements Reader
func ReadData(r Reader) {
buf := make([]byte, 100)
r.Read(buf)
}
Thus, interfaces in Go allow writing flexible and extensible code without tight coupling to specific types.