例一:菲波拉契数
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()) } //f() //1 //f() //1 //f() //2 //f() //3 //f() //5 //f() //8 //f() //13 //f() //21}
例二:为函数实现接口
//生成func fibonacci() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a }}func printFileContents(reader io.Reader){ scanner :=bufio.NewScanner(reader) for scanner.Scan() { fmt.Println(scanner.Text()) }}type intGen func() intfunc (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 main() { var f intGen = fibonacci() printFileContents(f)}
例三:使用函数遍历二叉树