liveBook · Manning

Interface embedding

As explained in Go by Example

Interface embedding is the inclusion of one interface's method set in another interface by naming the embedded interface.

Interface embedding includes one interface’s method set in another by naming the embedded interface. Go uses this composition to build larger, reusable interfaces from smaller protocols. section 7.3.2 section 7.8

Building io.ReadCloser

io.ReadCloser embeds io.Reader and io.Closer, so it provides both Read and Close without redeclaring either method. This makes its requirement clear: a value must support reading and closing. The same pattern appears in ReadWriteSeeker, which combines Reader, Writer, and Seeker. Naming conventions usually apply the -er suffix once, producing ReadCloser rather than ReaderCloser. section 7.3.2

type ReadCloser interface {
    Reader  #1
    Closer  #2
}

ReadCloser’s declaration shows interface embedding directly: Reader and Closer are named inside the larger interface, whose method set includes both. section 7.3.2

Embedding is useful when a larger protocol should preserve smaller, familiar contracts:

  • Avoids duplicating method declarations while clarifying which capabilities a type must provide. section 7.3.2
  • Supports incremental HTTP response-body processing through Reader and explicit resource release through Closer. section 7.3.2
  • Can add behavior around existing functionality, although embedding may hide methods and require type assertions to reveal optional interfaces. section 9.9

How Go by Example covers it

How deep it goes
Explains promoted methods, composition rationale, naming conventions, and practical I/O consequences; stops short of a broader language specification.
Examples
Uses io.ReadCloser, io.Reader, io.Closer, ReadWriteSeeker, HTTP response bodies, and io.NopCloser as concrete examples.
What you can do after
Apply interface embedding to compose smaller contracts, avoid duplication, clarify intent, and manage streamed resources.
How it connects
Connects interface embedding with composition, method sets, implicit interfaces, type assertions, dependency injection, and incremental I/O.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.