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.
Code
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
errbefore 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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.JSON Repair & InspectorDeterministically repair malformed JSON with trailing commas, comments, single quotes, unquoted keys, and Python literals alongside a repair log.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.