Why Is Program Method Being Called Implicitly Advice


(Joe Dan) #1

Hello,

I bought a new golang book and am stuck on an example small program that is in the book. Basically, I do not understand why the method is being called and ran automatically. From other examples I seen online if you want to use a method you actually have to call it. The example program is at this link golang playground . The method 'func (a *AngryReader) Read(b []bye) method is being called somehow and I just do not understand it. I would appreciate any kind of help I can get.

Thanks in advance,
Joe


(Norbert Melzer) #2

ioutil.ReadAll() is a wrapper around the io.Reader interface.

Every type that implements a Read(p []byte) (n int, err error) method is considered implementing the interface, thats why you are alowed to pass the AngryReader into ReadAll. That function will then subsequently call the arguments Read method until it sees an EOF and return the read bytes as a single slice.


(Joe Dan) #3

NobbZ,

I definitely thank you for such a quick response. I feel like I read something very similar from the book and I have no doubt your response is true and is the answer. However, I am having a very hard time understanding it as I am not a programmer. Is there a way you can reword your answer or maybe point me to some documentation online that might be a bit more for beginners? Either way thanks for your time and your help.

Joe


(Norbert Melzer) #4

There are links in my post, those + doing the tour should be enough to understand.

The simplest possible answer is just: “ReadAll” calls the Read method of whatever you pass in.


(Sean Killian) #5

Hi, Joe, The function isn’t being run automatically, what’s happening is that when you call ioutil.ReadAll with your AngryReader as an argument (a.k.a. parameter), ioutil.ReadAll is itself calling AngryReader’s Read function.