微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Golang Go语言结构体中匿名字段暴露方法的优先级

Golang Go语言结构体中匿名字段暴露方法的优先级

Go语言的结构体中可以包含匿名的字段,比如:

struct {
    T1       // 字段名自动为 T1
    *T2      // 字段名自动为 T2
    P.T3     // 字段名自动为 T3
    *P.T4    // 字段名自动为 T4
    x,yint  // 非匿名字段 x , y
}
如果构体 S,包含一个匿名字段 T,那么这个结构体 S 就有了 T的方法

如果包含的匿名字段为 *T,那么这个结构体 S 就有了 *T 的方法
如果S包含的匿名字段为 T或*T,那么 *S就有了 *T的方法

比如

type gzipResponseWriterstruct {
    io.Writer
}
因为 io.Writer里有 Write方法,所以 gzipResponseWriter 也有了 Write方法

var g gzipResponseWriter
g.Write(数据)

此处的 g.Write 就相当于 g.Writer.Write(数据)。

那么如果两个匿名字段都有同一个方法的时候,会怎么样呢?

type gzipResponseWriterstruct {
    io.Writer
    http.ResponseWriter
}
io.Writer这个接口已经有 Write方法了,http.ResponseWriter 同样有 Write方法。那么对 g.Write写的时候,到底调用哪个呢?是 g.Writer.Write 还是 g.ResponseWriter.Write呢?你不知道程序也不知道,如果编译就出现“Write模糊不清”的错误

怎么解决这个问题?

其一:就是重写 gzipResponseWriter的 Write方法,指明要写到哪一方。

func (w gzipResponseWriter) Write(b []byte) (int,os.Error) {
    returnw.Writer.Write(b)
}
上面这里就是指定使用 io.Writer里面的 Write方法


其二:使用匿名字段暴露方法优先级来确定重复方法的时候使用哪一个方法,原则就是【简单优先】。所以我们这里把 http.ResponseWriter弄复杂一点,使用另一个结构体先包裹一次。

type responseWriter struct {
    http.ResponseWriter
}
然后再在 gzipResponseWriter里面插入这个结构体
type gzipResponseWriterstruct {
    io.Writer
    responseWriter
}
这样就是 io.Writer的方法是会优先暴露出来的。这样就省去了上面那样的麻烦,而且当有多个重复方法的时候,还得一个一个来改写。记得使用 gzipResponseWriter 的时候原来的 类型为 http.ResponseWriter 的对象比如 w,要用 responseWriter{w},包装一下就可以使用到 gzipResponseWriter里面了,比如:创建 gzipResponseWriter 结构体变量的时候,原来比如使用 gzipResponseWriter{w,x} 就行,现在得使用 gzipResponseWriter{responseWriter{w},x},这其中 w是一个 http.ResponseWriter对象。


转and整理自:http://kejibo.com/golang-struct-anonymous-field-expose-method/

原文地址:https://www.jb51.cc/go/190669.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐