Essential Go Functions  Suggest an edit

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 using a variable (str) defined outside the function:

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

Functions using variables defined outside the function are called closures.

  ↑ ↓ to navigate     ↵ to select     Esc to close