How to Use Anonymous Functions (Closures) in Go

Define anonymous functions in Go using the func keyword without a name to create closures that capture surrounding variables.

Anonymous functions in Go are defined using the func keyword without a name and can be assigned to variables or passed as arguments. They capture variables from their surrounding scope, forming closures that retain access to those variables even after the outer function returns.

package main

import "fmt"

func main() {
	// Define an anonymous function
	add := func(a, b int) int {
		return a + b
	}

	// Use the anonymous function
	fmt.Println(add(2, 3)) // Output: 5

	// Closure example: capturing 'multiplier'
	multiplier := 10
	multiply := func(x int) int {
		return x * multiplier
	}

	fmt.Println(multiply(5)) // Output: 50

	// Passing anonymous function as argument
	process := func(fn func(int) int, val int) {
		fmt.Println(fn(val))
	}
	process(multiply, 3) // Output: 30
}