What Are Interfaces in Go and How Do They Work

Go interfaces define method sets that concrete types implement to enable polymorphism and decoupled code design.

Interfaces in Go are type definitions that specify a set of method signatures that a concrete type must implement to satisfy the interface. They enable polymorphism by allowing functions to accept any type that implements the required methods, without knowing the concrete type at compile time.

type Reader interface {
    Read(p []byte) (n int, err error)
}

func Copy(r Reader) {
    // r can be any type implementing Read, e.g., bytes.Reader
    var buf [1024]byte
    r.Read(buf[:])
}