Embedded interfaces
April 17, 2023
Embedded interfaces
In a slightly more general form an interface
T
may use a (possibly qualified) interface type nameE
as an interface element. This is called embedding interfaceE
inT
. The type set ofT
is the intersection of the type sets defined byT
’s explicitly declared methods and the type sets ofT
’s embedded interfaces. In other words, the type set ofT
is the set of all types that implement all the explicitly declared methods ofT
and also all the methods ofE
.type Reader interface { Read(p []byte) (n int, err error) Close() error } type Writer interface { Write(p []byte) (n int, err error) Close() error } // ReadWriter's methods are Read, Write, and Close. type ReadWriter interface { Reader // includes methods of Reader in ReadWriter's method set Writer // includes methods of Writer in ReadWriter's method set }
When embedding interfaces, methods with the same names must have identical signatures.
type ReadCloser interface { Reader // includes methods of Reader in ReadCloser's method set Close() // illegal: signatures of Reader.Close and Close are different }
Similar to the way structs may have embedded fields, interfaces can be embedded as well. Although there are a couple of key differences:
- The name of the embedded interface has no bearing on the outter interface. With structs, the name of the embedded type becomes an implicit struct field name.
- Methods of the same name must have identical signatures. With structs, the outter-most definition of a field takes precidence over any embedded field of the same name.
Quotes from The Go Programming Language Specification Version of December 15, 2022