7.2 函数式编程例一
一、Go语言闭包应用
斐波那契数列
package main import "fmt" // 斐波那契数列:前两个是1,第三个开始,每一个值都是前两个值的和 // 生成器,生成斐波那契数列 func fibonacci() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }为函数实现接口(非手动输出)
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() //for i := 0; i < 10; i++ { // fmt.Println(f()) //} printFileContents(f) }
Last updated
Was this helpful?