typestar

Embedding interfaces in Go

A bigger interface is built from smaller ones, which is how io does it.

type Reader interface {
    Read(p []byte) (int, error)
}

type Closer interface {
    Close() error
}

type ReadCloser interface {
    Reader
    Closer
}

type memoryFile struct {
    data   []byte
    offset int
}

func (m *memoryFile) Read(p []byte) (int, error) {
    if m.offset >= len(m.data) {
        return 0, io.EOF
    }
    n := copy(p, m.data[m.offset:])
    m.offset += n
    return n, nil
}

func (m *memoryFile) Close() error { return nil }

var _ ReadCloser = (*memoryFile)(nil)

How it works

  1. Embedding lists the method sets to combine.
  2. io.ReadWriter is exactly Reader plus Writer.
  3. Accepting the smallest interface you need is the Go habit.

Keywords and builtins used here

The run, in numbers

Lines
30
Characters to type
444
Tokens
133
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 3 of 4 in Interfaces, step 6 of 19 in Interfaces & generics.

← Previous Next →