Search code examples
arraysgoinfinite-loop

How does calling reader.Validate(MyReader{}) calls my custom Read method?


https://github.com/golang/tour/blob/master/solutions/readers.go

package main

import "golang.org/x/tour/reader"

type MyReader struct{}

func (r MyReader) Read(b []byte) (int, error) { . //Q1) How is this method getting called?
//Q2) Its no where called in this source code
//Q3) What is the length of b ?
    for i := range b { //Q4) Why isn't throwing an infinite loop ?
        b[i] = 'A' 
    }
    return len(b), nil
}

func main() {
    reader.Validate(MyReader{})
}

Solution

  • it calls Read(b []byte) look at the source here https://github.com/golang/tour/blob/master/reader/validate.go#L17

    Validate(io.Reader) expects an io.Reader, which only needs a Read([]byte) function to fullfill the interface. That is what you're doing, so Validate can call your reader.