Essential Go Functions  Edit on GitHub      File Issue

Function literals

A function literal is a function declared inline, without a name.

Simplest example of a function literal:

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

Function literal with arguments:

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

Function literal closing over variable str:

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

Function that closes over variables is called a closure.

  ↑ ↓ to navigate     ↵ to select     Esc to close