Go Function Closures (Anonymous Functions)
Go supports anonymous functions, which can be used as closures. An anonymous function is an "inline" statement or expression. Its advantage is that it can directly use variables within the function without having 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 a function argument.
In the following example, we create a function getSequence() that returns another function. The purpose of that function is to increment the variable i within the closure, as shown in the code below:
Example
package
main
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 variable i is incremented by 1 and returned */
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 code above is:
1
2
3
1
2
In the following example, we define several anonymous functions and demonstrate how to assign an anonymous function to a variable, use an anonymous function inside a function, and pass an anonymous function as an argument to another function.
Example
package
main
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 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 execution result of the code above is:
3 + 5 = 8
4 * 6 = 24
2 + 8 = 10
10 - 4 = 6
The use of anonymous functions is very flexible in Go, helping to simplify code structure and improve readability.
Go Functions