调用 reader.Validate(MyReader{}) 如何调用我的自定义 Read 方法?
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{})
}
它调用 Read(b []byte) 在这里查看源代码 https://github.com/golang/tour/blob/master/reader/validate.go#L17
Validate(io.Reader) 需要一个 io.Reader,它只需要一个 Read([]byte) 函数来填充接口。这就是您正在做的,因此 Validate 可以调用您的 reader.
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{})
}
它调用 Read(b []byte) 在这里查看源代码 https://github.com/golang/tour/blob/master/reader/validate.go#L17
Validate(io.Reader) 需要一个 io.Reader,它只需要一个 Read([]byte) 函数来填充接口。这就是您正在做的,因此 Validate 可以调用您的 reader.