假设有两个接口类型如下:
type I1 interface { Val1() string }
type I2 interface { Val2() string }
然后有结构体如下:
type T struct {}
func (t *T) Val1() string { return "t val1" }
func (t *T) Val2() string { return "t val2" }
现在定一个I1的包装器
type Wrapper struct {I1}
使用这个包装器
t := T{}
wrap := Wrapper { t }
问题是:通过 wrap 可以直接访问I1接口定义的方法,但是传递的对象t也实现了I2接口,但是无法通过 wrap 访问I2的接口方法:
wrap.Val1() // OK!
t.(I2).Val2() // OK!
wrap.(I2).Val2() // Panic!
有什么办法能让 wrap.(I2).Val2() 可以干活不?
于是 golang adapter interface 谷歌一番,得到一些结果:
proposal: Go 2: interface adapter types 说明 go 目前还不直接指出这种使用方式,有人在提 proposal,但是被关闭了(拒了),俱乐不要紧,评论信息还是值得看一下的
Interface wrapping method erasure(link:https://medium.com/@cep21/interface-wrapping-method-erasure-c523b3549912)
// WrapWriter wraps an http.ResponseWriter, returning a proxy that allows you to
// hook into various parts of the response process.
func WrapWriter(w http.ResponseWriter) WriterProxy {
_, cn := w.(http.CloseNotifier)
_, fl := w.(http.Flusher)
_, hj := w.(http.Hijacker)
_, rf := w.(io.ReaderFrom)
bw := basicWriter{ResponseWriter: w}
if cn && fl && hj && rf {
return &fancyWriter{bw}
}
if fl {
return &flushWriter{bw}
}
return &bw
}
结论是,目前还不能直接那么玩。

