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
- Q88Embedding
Tvs*T: how does each affect the method set of the outer struct? - Q89What happens when two embedded types provide the same field or method name?
- Q91Why would you embed an interface inside a struct? What is the danger?
- Q92When should you use
any(interface{}), and when are generics the better choice? - Q93What does
var _ io.Writer = (*MyWriter)(nil)do, and why is it used? - Q94Go interfaces are satisfied implicitly. What design consequences follow, and where should interfaces be defined?