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 gzipResponseWriterg.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/
总结以上是内存溢出为你收集整理的Golang Go语言结构体中匿名字段暴露方法的优先级全部内容,希望文章能够帮你解决Golang Go语言结构体中匿名字段暴露方法的优先级所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)