deoren / notes

Various notes for topics I'm learning
2 stars 0 forks source link

Golang | Closures, anonymous functions, return functions #62

Open deoren opened 5 years ago

deoren commented 5 years ago

The scratch notes are borrowed from elsewhere for further review.

package main

import "fmt"

// receive an int, return an anonymous function (which takes an int and
// returns an int)
// NOTE: the original argument is still accessible to the anonymous function
// when called later
// e.g., `fn := makeAddr(1); fmt.Println(fn(2))` results in three being printed
func makeAdder(b int) func(int) int {
    return func(a int) int {
        return a + b
    }
}

func main() {

    addOne := makeAdder(1)
    addTwo := makeAdder(2)

    fn := makeAdder(1)
    fmt.Println(fn(2))

    fmt.Println(addOne(1))
    fmt.Println(addTwo(1))

}
deoren commented 5 years ago

See also #57