Go language function closures (anonymous functions)
The Go language supports anonymous functions, which can be used as closures. An anonymous function is an "inline" statement or expression. The advantage of anonymous functions is that they can directly use variables within the function without needing to declare them.
An anonymous function is a function without a function name, typically used to define functions inside other functions, or to be passed as function parameters.
In the following example, we create the function getSequence(), which returns another function. The purpose of that function is to increment the variable i within a closure, as shown in the code below:
Example
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* nextNumber is a function, with i initialized to 0 */
nextNumber := getSequence()
/* Call the nextNumber function, the i variable increments by 1 and returns */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* Create a new function nextNumber1 and check the result */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
The execution result of the above code is:
1 2 3 1 2
In the following examples, we define multiple anonymous functions and demonstrate how to assign anonymous functions to variables, use anonymous functions inside other functions, and pass anonymous functions as arguments to other functions.
Example
import "fmt"
func main() {
// Define an anonymous function and assign it to the variable add
add := func(a, b int) int {
return a + b
}
// Call the anonymous function
result := add(3, 5)
fmt.Println("3 + 5 =", result)
// Use an anonymous function inside a function
multiply := func(x, y int) int {
return x * y
}
product := multiply(4, 6)
fmt.Println("4 * 6 =", product)
// Pass an anonymous function as an argument to other functions
calculate := func(operation func(int, int) int, x, y int) int {
return operation(x, y)
}
sum := calculate(add, 2, 8)
fmt.Println("2 + 8 =", sum)
// You can also define an anonymous function directly in a function call
difference := calculate(func(a, b int) int {
return a - b
}, 10, 4)
fmt.Println("10 - 4 =", difference)
}
The execution result of the above code is:
3 + 5 = 8 4 * 6 = 24 2 + 8 = 10 10 - 4 = 6
The use of anonymous functions in Go is very flexible and can help simplify code structure and improve code readability.
other extensions