resp.Body如何实现Read函数?

huangapple go评论81阅读模式
英文:

How does resp.Body implements the Read function?

问题

我目前正在学习Go语言,并试图理解接口的概念。
我理解的是,任何实现了接口中指定函数的类型都是该接口的一部分。
我的问题是关于Response结构体中的io.ReadCloser类型的Body字段。它是如何实现Read函数的?我已经在文档中搜索过,但没有找到相关信息。

英文:

I'm currently studying Go and trying to understand the concept of Interfaces.
What I understand about it is that whatever type implements the functions specified in the interface is part of it.
My question is about the Body of type io.ReadCloser inside of the Response struct. How does it implement the Read function? I've searched through the documentation and couldn't find it.

答案1

得分: 0

io.ReadCloser没有实现Read函数。io.ReadCloser是一个接口类型,因此它本身不能实现任何方法。然而,如果T类型集I子集,则接口T可以实现另一个接口I


io.ReadCloser接口嵌入了io.Readerio.Closer接口。因此,io.ReadCloser的方法集是io.Readerio.Closer的方法集的组合。

通过嵌入io.ReadCloser的类型集是io.Reader的类型集和io.Closer的类型集的交集。换句话说,io.ReadCloser的类型集是所有实现io.Readerio.Closer接口的类型的集合。

上述也意味着io.ReadCloser的类型集是io.Reader的类型集和io.Closer的类型集的子集。

io.ReadCloser接口实现io.Reader,因为:

> 如果类型T满足以下条件,则类型T实现接口I:
>
> - T不是接口,并且是I的类型集的元素;或者
> - T是接口,并且T的类型集是I的类型集的子集。

英文:

io.ReadCloser does not implement the Read function. io.ReadCloser is an interface type, so it by itself cannot implement any methods. However, an interface T can implement another interface I if T's type set is a subset of I.


The io.ReadCloser interface embeds the io.Reader and io.Closer interfaces. Therefore the method set of io.ReadeCloser is the combined method set of io.Reader and io.Closer.

Thanks to embedding the type set of io.ReadCloser is the intersection of io.Reader's and io.Closer's type sets. In other words the type set of io.ReadCloser is the set of all types that implement the io.Reader and io.Closer interfaces.

The above also means that the type set of io.ReadCloser is a subset of io.Reader's type set and io.Closer's type set.

The io.ReadCloser interface implements io.Reader because:

> A type T implements an interface I if
>
> - T is not an interface and is an element of the type set of I; or
> - T is an interface and the type set of T is a subset of the type set of I.

huangapple
  • 本文由 发表于 2022年9月10日 11:16:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73669041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定