How do interfaces work in Go

Go interfaces define method sets that types implicitly satisfy, enabling flexible and type-safe polymorphism.

Go interfaces define a set of method signatures that a type must implement to satisfy the interface, enabling polymorphism without explicit inheritance. When a type implements all methods of an interface, it automatically satisfies that interface without needing a declaration.

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

type MyReader struct { data []byte }

func (m *MyReader) Read(b []byte) (n int, err error) {
    // implementation
    return
}

// MyReader automatically satisfies the Reader interface
var r Reader = &MyReader{data: []byte("hello")}