congdong007

Penetration Test、Software Developer

0%

Closure and Anonymous Function in Go

In Go language, closures and anonymous functions are both forms of functions, but they have some important differences. Below, I will provide examples of the usage and differences between these two concepts:

  1. Closure Example:
    A closure refers to a function that captures one or more variables from its outer function scope and can be called outside of that function while still accessing these captured variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
outerVar := 10

// Closure function
closure := func() {
fmt.Println("Outer variable outerVar:", outerVar)
}

// Call the closure function
closure() // Output: Outer variable outerVar: 10

// Modify the outer variable
outerVar = 20

// Call the closure function again
closure() // Output: Outer variable outerVar: 20
}

In the above example, closure is a closure that captures the outer variable outerVar and can access and modify that variable even outside the function.

  1. Anonymous Function Example:

An anonymous function is a function without a name; it can be directly assigned to a variable or passed as an argument to other functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import "fmt"

func main() {
// Define and call an anonymous function
result := func(x, y int) int {
return x + y
}(5, 3)

fmt.Println("Result of the anonymous function:", result) // Output: Result of the anonymous function: 8

// Assign an anonymous function to a variable
add := func(x, y int) int {
return x + y
}

sum := add(10, 20)
fmt.Println("Calling the anonymous function using a variable:", sum) // Output: Calling the anonymous function using a variable: 30
}

In the above example, we define an anonymous function and call it directly. We also assign another anonymous function to the add variable and use that variable to call the function.

To summarize the differences:

A closure is a function that captures external variables and can access and modify them outside of the function.
An anonymous function is a function without a name, which can be assigned to a variable or passed as an argument to other functions.
It’s important to note that while closures often involve anonymous functions, not all anonymous functions are closures. A closure is a specific type of anonymous function that captures external variables.