A simple literal function, printing Hello!
to stdout:
package main
import "fmt"
func main() {
func(){
fmt.Println("Hello!")
}()
}
A literal function, printing the str
argument to stdout:
package main
import "fmt"
func main() {
func(str string) {
fmt.Println(str)
}("Hello!")
}
A literal function, closing over the variable str
:
package main
import "fmt"
func main() {
str := "Hello!"
func() {
fmt.Println(str)
}()
}
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()
}