bingoohuang/blog

GOLANG中基于接口的适配器

Opened this issue · 0 comments

假设有两个接口类型如下:

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谷歌一番,得到一些结果:

  1. proposal: Go 2: interface adapter types 说明go目前还不直接指出这种使用方式,有人在提proposal,但是被关闭了(拒了),俱乐不要紧,评论信息还是值得看一下的

  2. Interface wrapping method erasure

    // 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
    }

结论是,目前还不能直接那么玩。