gpt4 book ai didi

go - 在 Go 中仅指定一个结构类型作为结构成员是什么意思?

转载 作者:IT王子 更新时间:2023-10-29 00:39:39 25 4
gpt4 key购买 nike

我知道我可以写这样的代码,但我不知道它是如何工作的:

type MyTransport struct {
http.Transport
}

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

http.Transport 只是一个结构,对吧?它没有名字。那么 myT.Transport 是如何工作的呢?为什么我不必在 MyTransport 中为传输命名,例如声明为 ht http.Transport

最佳答案

这是一个嵌入式结构,来自 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.

长话短说:

这就是 go 的“oop”继承方式,或多或少:

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

关于go - 在 Go 中仅指定一个结构类型作为结构成员是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com