Compose Interfaces By Embedding

Build a composite interface by embedding io.Reader and io.Closer plus your own method, so callers depend on capability sets instead of concrete types.

GoResilience

Code

gosnippet
40 lines
package main

import (
	"fmt"
	"io"
	"strings"
)

// 嵌入已有接口组成新接口:声明内嵌接口名即可,无需重写方法签名
type ReadClosingLimiter interface {
	io.Reader
	io.Closer
	Limit() int
}

type source struct {
	r     *strings.Reader
	limit int
}

func (s *source) Read(p []byte) (int, error) { return s.r.Read(p) }
func (s *source) Close() error               { return nil }
func (s *source) Limit() int                 { return s.limit }

func drain(rc ReadClosingLimiter) string {
	defer rc.Close() // 满足 io.Closer 的调用点无需关心具体类型
	out, err := io.ReadAll(rc)
	if err != nil {
		return "read failed: " + err.Error()
	}
	return string(out)
}

func main() {
	s := &source{r: strings.NewReader("config body"), limit: 64}
	// *source 实现全部三个方法集,隐式满足组合接口
	var rc ReadClosingLimiter = s
	fmt.Println(drain(rc))
	fmt.Println("limit:", rc.Limit())
}

How it works

All of the logic lives in the functions Read, Close, Limit and drain.

Failures are values here: 1 site check err and decide instead of letting one propagate. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

What to watch for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Putting it to use

The signature in play: func (s *source) Read(p []byte) (int, error)

Running the file prints labeled results such as limit: — each operation’s effect is visible in the output.

The sequence drain and Limit lives in main; running the file triggers it.

The core lines, annotated

func (s *source) Read(p []byte) (int, error) { return s.r.Read(p) }
func (s *source) Limit() int                 { return s.limit }
func (s *source) Close() error               { return nil }

Interactive Tools for This Topic

FAQ

What is the error handling style?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
What does Compose Interfaces By Embedding print when run?
Execute the whole file; each printed line is prefixed with a label like `limit:`.