函数实现接口
package main
import (
"bufio"
"fmt"
"io"
"strings"
)
func fibonacci() intGen {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
type intGen func() int
func (g intGen) Read(p []byte) (n int, e error) {
next := g()
if next > 1000 {
return 0, io.EOF
}
s := fmt.Sprintf("%d\n", next)
return strings.NewReader(s).Read(p)
}
func main() {
f := fibonacci()
s := bufio.NewScanner(f)
for s.Scan() {
fmt.Println(s.Text())
}
}
- 函数是一等公民
- 函数可以做为参数