Go

What is interface embedding, and what changed in Go 1.14 about overlapping methods?

Question 90MediumGo 1.22 to 1.25

An interface can embed other interfaces. The resulting method set is the union of all their methods. This is how the standard library builds larger contracts from small ones:

type Reader interface{ Read(p []byte) (int, error) }
type Writer interface{ Write(p []byte) (int, error) }
type Closer interface{ Close() error }

type ReadWriteCloser interface {
    Reader
    Writer
    Closer
}

// Go 1.14+: overlapping identical methods are allowed
type ReadCloser interface {
    Reader
    Closer
}
type WriteCloser interface {
    Writer
    Closer
}
type RWC2 interface {
    ReadCloser
    WriteCloser // Close appears twice: OK since Go 1.14
}

Before Go 1.14, a method that appeared in two embedded interfaces was a "duplicate method" compile error, even when the signatures were identical. Since Go 1.14, duplicate methods with identical signatures merge. Methods with the same name and different signatures are still an error.

Since generics arrived (Go 1.18), interfaces can also embed type elements (~int | ~string) and comparable. Such interfaces become constraint-only interfaces and cannot be used as ordinary value types.

More on Interfaces, Methods & Embedding

All 35 Interfaces, Methods & Embedding questions