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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程