Fragment Description:



Closures, briefly, are functions that carry along with them variables declared within lexical scope of the defined function.
So, what does this mean? The variable 'foo' is in scope for the function that we declare and return from a Func().
When we return our function, foo stays in scope, even though the function it was declared in has returned.


closureFuncAnExample

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:32

/* ... <== see fragment description ... */

package main

import "fmt"

type generator func() int

func aFunc() generator {
    foo := 0
    // the returned function of type generator is a closure, it encompasses the
    // var foo.
    return func() int {
        foo++
        return foo
    }
}
func main() {
    bar := aFunc()
    fmt.Println(bar())     // 1
    fmt.Println(bar())     // 2
    fmt.Println(bar() - 3) // 1
}

/* Expected Output:
1
2
0
*/



Comments