Home > database >  How does resp.Body implements the Read function?
How does resp.Body implements the Read function?

Time:09-13

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.

CodePudding user response:

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.
  • Related