Home »
Golang
Go Function Closure
Last Updated : July 19, 2025
In Go, a closure is a function value that references variables from outside its body. The function can access and modify these variables even after the outer function has finished execution. Closures are often used for maintaining state or creating factory functions.
What is a Closure in Go?
A closure in Go is essentially an anonymous function that "remembers" the variables from the scope where it was defined, even after that scope has exited.
Example: Basic Closure
The following example demonstrates a closure in Go, where the returned function retains access to the count variable from its surrounding scope, allowing it to maintain state across multiple calls:
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := counter()
fmt.Println(next())
fmt.Println(next())
fmt.Println(next())
}
When you run the above code, the output will be:
1
2
3
Explanation
The counter()
function returns another function (a closure) that increments and returns a local variable count
. Even though the outer function finishes, the inner function retains access to count
and modifies it on each call.
Another Example: Closure with Parameters
This Go program demonstrates closures - functions that reference variables from outside their own body:
package main
import "fmt"
func multiplier(factor int) func(int) int {
return func(n int) int {
return n * factor
}
}
func main() {
double := multiplier(2)
triple := multiplier(3)
fmt.Println(double(5)) // 10
fmt.Println(triple(5)) // 15
}
When you run the above code, the output will be:
10
15
Exercise
Check your understanding of closures in Go:
- What is a closure?
- Does a closure keep access to local variables of its outer function even after the outer function returns?
- In the example above, what does calling
next()
multiple times do?
Advertisement
Advertisement