dongmu5815 2014-06-06 21:22
浏览 17
已采纳

在Go中仅将结构类型指定为结构成员是什么意思?

I know I can write code like this, but I don't know how it works:

type MyTransport struct {
  http.Transport
}

func (myT *MyTransport) RoundTrip(r *http.Request) (*http.Response, error) {
  return myT.Transport.RoundTrip(r)
}

http.Transport is just a struct, right? It has no name. So how does myT.Transport work? Why do I not have to give the transport a name in MyTransport, such as declaring it like ht http.Transport?

  • 写回答

4条回答 默认 最新

  • doucan4873 2014-06-06 21:31
    关注

    That's an embedded struct, from http://golang.org/doc/effective_go.html#embedding :

    By embedding the structs directly, we avoid this bookkeeping. The methods of embedded types come along for free, which means that bufio.ReadWriter not only has the methods of bufio.Reader and bufio.Writer, it also satisfies all three interfaces: io.Reader, io.Writer, and io.ReadWriter.

    There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one. In our example, when the Read method of a bufio.ReadWriter is invoked, it has exactly the same effect as the forwarding method written out above; the receiver is the reader field of the ReadWriter, not the ReadWriter itself.

    Embedding can also be a simple convenience. This example shows an embedded field alongside a regular, named field.

    TL;DR:

    That's go's way of "oop" inheritance, more or less:

    type MyTransport struct {
        http.Transport
    }
    
    //without this function, calling myT.RoundTrip would actually call myT.Transport.RoundTrip
    func (myT *MyTransport) RoundTrip(r *http.Request) (*http.Response, error) {
        return myT.Transport.RoundTrip(r)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线