Go中写适配器是为解决已有接口间调用不匹配的硬性问题,如*http.Client与Doer接口不兼容,或方法名/签名差异;必须严格匹配方法签名,嵌入+覆盖可简化实现,单方法接口优先用函数适配器。

Go 里写适配器,不是为了“模拟类继承”,而是为了解决两个已有接口之间调用不上的硬问题——比如你手上有 *http.Client,但下游函数只接受 Doer 接口;或者第三方日志库的 LogInfo(string) 方法,和你定义的 Logger.Info(string) 名字/签名差了一点。这时候加个适配器,不是设计选择,是编译器逼你做的。
为什么 *MyType 传不进 SomeInterface?先看方法签名是否真匹配
常见错误信息:cannot use myImpl (type *MyService) as type OtherInterface in argument to consume: *MyService does not implement OtherInterface。这不是语法错误,是 Go 编译器在告诉你:它比对了所有方法,发现至少一个不一致。
- 方法名大小写必须完全一样(
Info≠info) - 参数类型不能“差不多”——
int和int64不兼容,error和*errors.Error也不等价 - 返回值顺序、数量、类型必须严格一致;多一个
error或少一个context.Context都不行 - 如果原类型方法用的是指针接收者(如
func (s *Service) Do()),那你必须传*Service,不能传Service值类型
用嵌入 + 方法覆盖,比从头写 struct wrapper 更省事
当你发现目标接口只比原类型多一两个方法,或仅参数名/顺序不同,别逐个重写全部方法。直接嵌入原类型,再只覆盖差异部分即可:
type LegacyAPI struct{}</code><code>func (l *LegacyAPI) Get(url string) (string, error) { /* ... */ }</code><p><code>type Fetcher interface { Fetch(string) ([]byte, error) }</code></p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">go语言免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill6460" title="Golang Naming"><img
src="https://img.php.cn/upload/skill/000/000/081/179094616043400.jpg" alt="Golang Naming" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill6460" title="Golang Naming">Golang Naming</a>
<p>Go(Golang)命名规范 — 包括包、构造函数、结构体、接口、常量、枚举、错误、布尔值、接收器、getter/setter、函数等。</p>
</div>
<a href="/xiazai/skill6460" title="Golang Naming" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><code>type APIAdapter struct{ <em>LegacyAPI }</code><code>func (a </em>APIAdapter) Fetch(url string) ([]byte, error) {</code><code> s, err := a.Get(url)</code><code> return []byte(s), err</code><code>}注意:*LegacyAPI 是指针嵌入,这样能透传所有指针接收者方法;如果嵌入的是 LegacyAPI(值类型),且其方法全是 (*T).M,那嵌入后无法自动提升。
单方法接口优先用函数适配器,别套 struct
像 http.Handler、io.Writer、fmt.Stringer 这类只有一个方法的接口,函数转接口最干净:
type HandlerFunc func(http.ResponseWriter, *http.Request)</code><code>func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { f(w, r) }</code><p><code>// 直接用,无需定义新 struct</code><code>http.Handle("/ping", HandlerFunc(func(w http.ResponseWriter, r *http.Request) {</code><code> w.Write([]byte("ok"))</code><code>}))这种模式在标准库中大量存在,轻量、易测、无额外内存分配。只有当需要携带状态(比如带配置的 logger)、或目标接口有多个方法时,才考虑 struct wrapper。
空指针、context 丢失、error 包装——三个地方最容易漏检查
适配器不是透明管道,它是一层显式转换逻辑。这三个坑在压测或上线后才暴露:
- 嵌入字段为 nil 时直接 panic:在构造函数里加校验,比如
if src == nil { panic("nil adaptee") } - 原接口支持
context.Context,目标接口没暴露——别默默丢掉,要么用context.Background()显式降级,要么把 context 提到参数里(需上下游协同) - 错误未包装就返回:原方法返回
errors.New("timeout"),你直接return nil, err没问题;但如果要加 trace ID 或统一错误码,得用fmt.Errorf("fetch failed: %w", err)包装,否则调用方的错误断言会失败
真正难的不是写适配器,是判断该不该写——有时候改调用方接口、或让被适配方升级,比套一层 wrapper 更可持续。

















