Nested and Anonymous Functions


Functions can be nested, instantiated, assigned to variables, and have access to its parent function's variables.

package main

import (
    "fmt"
)

func main() {
    var counter int = 1

    func(str string) {
        fmt.Println("Hi", str, "I'm an anonymous function")
    }("Ricky")

    funcVar := func(str string) {
        fmt.Println("Hi", str, "I'm an anonymous function assigned to a variable.")
    }

    funcVar("Johnny")

    closure := func(str string) {
        fmt.Println("Hi", str, "I'm a closure.")
        for i := 1; i < 5; i++ {
            fmt.Println("Counter incremented to:", counter)
            counter++
        }
    }

    fmt.Println("Counter is", counter, "before calling closure.")
    closure("Sandy")
    fmt.Println("Counter is", counter, "after calling closure.")
}

Output

Hi Ricky I'm an anonymous function
Hi Johnny I'm an anonymous function assigned to a variable.
Counter is 1 before calling closure.
Hi Sandy I'm a closure.
Counter incremented to: 1
Counter incremented to: 2
Counter incremented to: 3
Counter incremented to: 4
Counter is 5 after calling closure.

results matching ""

    No results matching ""