Anonymous functions

// example anon function
world := func() {
	fmt.Println("Hello world")
}
 
// functions as inputs
func customMsg(fn func(m string), msg string) {
	msg = strings.ToUpper(msg)
	fn(msg) // <- calls the function given
}
 
// functions as outputs
func makeFunction() func(a, b int) int {
	return func(a, b int) {
		return a + b
	}
}

Closure

  • allows the use of local variables in a anon function
func main() {
	message := "Hello there buddy"
	fn := func() string {
		fmt.Println(message)
		return strings.ToLower(message)
	}
	// fn can be sent as a parameter or returned and used elsewhere and message will still have the value of "Hello there buddy"
}