Go Function Closure return a function

Introduction

One way to use closure is by writing a function that returns another function.

For example, here's how we might generate all the even numbers:

package main/*from   ww  w.ja v  a 2s. com*/

import "fmt" 

func makeEvenGenerator() func() uint { 
    i  := uint(0) 
    return func() (ret uint) { 
        ret = i 
        i += 2 
        return 
    } 
} 
func main() { 
    nextEven  := makeEvenGenerator() 
    fmt.Println(nextEven()) // 0 
    fmt.Println(nextEven()) // 2 
    fmt.Println(nextEven()) // 4 
} 



PreviousNext

Related