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条)

报告相同问题?