Go Literal functions & closures


Example

A simple literal function, printing Hello! to stdout:

package main

import "fmt"

func main() {
    func(){
        fmt.Println("Hello!")
    }()
}

play it on playground


A literal function, printing the str argument to stdout:

package main

import "fmt"

func main() {
    func(str string) {
        fmt.Println(str)
    }("Hello!")
}

play it on playground


A literal function, closing over the variable str:

package main

import "fmt"

func main() {
    str := "Hello!"
    func() {
        fmt.Println(str)
    }()
}

play it on playground


It is possible to assign a literal function to a variable:

package main

import (
    "fmt"
)

func main() {
    str := "Hello!"
    anon := func() {
        fmt.Println(str)
    }
    anon()
}

play it on playground