麻烦大神们看下这个问题

package main

import (
   "bufio"
   "fmt"
   "io"
   "strings"
)

type IntFunc func() int

func fibonacci() IntFunc {
   a, b := 0, 1
   return func() int {
      a, b = b, a+b
      return a
   }
}

func (f IntFunc) Read(b []byte) (i int, err error) {

   next := f()

   if next > 10000 {
      return 0, io.EOF
   }

   s := fmt.Sprintf("%d\n", next)

   return strings.NewReader(s).Read(b)

}

func printFileContents(reader io.Reader) {

   scanner := bufio.NewScanner(reader)

   for scanner.Scan() {
      fmt.Printf("%s \n", scanner.Text())
   }

}

func main() {
   f := fibonacci()

   printFileContents(f)
}
为什么形参是一个io.Reader  实参是一个函数  而不报错
艾帆的笑
浏览 804回答 1
1回答

pardon110

io.Reader并不是形参,它是一个接口类型,其签名如下所示type Reader interface {         Read(p []byte) (n int, err error) }真正的形参是reader。之所以实参是一个函数而不出错,是因为作为方法的接收者,该函数InFunc类型,隐性实现了接口io.Reader的Read方法,换而言之,该实参函数类型也是一个io.Reader类型。而其实现接口体现在这句func (f IntFunc) Read(b []byte) (i int, err error) {...
打开App,查看更多内容
随时随地看视频慕课网APP