Golang:打印斐波那契数列(利用Read接口)

/ Golang / 没有评论 / 2027浏览

Golang函数式编程

package main

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

type IntGen func() int


//实现Read接口
func (g IntGen) Read(p []byte) (n int, err error) {
	next := g()

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

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

	return strings.NewReader(s).Read(p)
}

//读取reader里面的内容
func printFileContents(reader io.Reader){
	scanner := bufio.NewScanner(reader)

	for scanner.Scan(){
		fmt.Println(scanner.Text())
	}
}

func filb() IntGen {
	a, b := 0,1
	return func() int{
		a ,b = b,a + b
		return a
	}
}

func main() {
	f := filb()

	printFileContents(f)
}