functions5.goΒΆ

// functions5.go

package main

import (
    "fmt"
)

func makeAdder1(n int) func(int) int {
    // n is local to makeAdder1
    f := func(a int) int { // closure
        return n + a // what does n refer to?
    }
    return f
}

func test1() {
    add1 := makeAdder1(1)
    fmt.Println(add1(add1(3)))
}

func main() {
    test2()
}

func makeAdder2() (func() int, func() int) {
    i := 0
    add := func() int { // this is a closure because i is not local to add
        i++
        return i
    }
    get := func() int { // this is a closure because i is not local to get
        return i
    }
    // add and get are closures because they refer to a variable, i
    // in this case, not defined in the function

    return add, get // i escapes from makeAdder2
}

func test2() {
    incr, getter := makeAdder2()
    fmt.Println(getter())
    incr()
    incr()
    fmt.Println(getter())
}