Go函数式编程主要体现在使用闭包上面。
比较常见的就是基于自由变量的闭包如下面的Fibonacci。
但是不常见的也有基于函数的闭包。
将两个例子合并为一起。
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, err error) {
next := g()
if next > 10000 {
return 0, io.EOF
}
s := fmt.Sprintf("%d\n", next)
return strings.NewReader(s).Read(p)
}
func printFileContents(reader io.Reader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func main() {
f := Fibonacci()
printFileContents(f)
}