YouTip LogoYouTip

Go Function Closures

# Go Function Closures (Anonymous Functions) [![Image 3: Go Functions](#)Go Functions](#) Go supports anonymous functions, which can form closures. Anonymous functions are "inline" statements or expressions. 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 name, typically used to define a function inside another function or to be passed as an argument to other functions. In the following example, we create a function `getSequence()` which returns another function. The purpose of this function is to increment the variable `i` within a closure, as shown in the code below: ## Example ```go package main import "fmt" func getSequence() func() int { i := 0 return func() int { i += 1 return i } } func main() { /* nextNumber is a function, where variable i is 0 */ nextNumber := getSequence() /* Call nextNumber function, increment variable i by 1 and return */ 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 result of the above code execution is: 1 2 3 1 2 In the following example, 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 ```go package main import "fmt" func main() { // Define an anonymous function and assign it to 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 another 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 another function 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 result of the above code execution is: 3 + 5 = 8 4 * 6 = 24 2 + 8 = 10 10 - 4 = 6 The use of anonymous functions is very flexible in Go and can help simplify code structure and improve code readability. [![Image 4: Go Functions](#)Go Functions](#)
← Go Function As ValuesGo Function Call By Value β†’