How to Create Function Closures in Go

Create a Go function closure by defining an anonymous function that captures outer scope variables and returns it.

Create a function closure by defining an anonymous function that captures variables from its surrounding scope and assigning it to a variable or returning it immediately. The closure retains access to the outer variables even after the outer function returns.

func makeAdder(x int) func(int) int {
	return func(y int) int {
		return x + y
	}
}

add5 := makeAdder(5)
result := add5(3) // result is 8