×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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:

  1. What is a closure?
  2. Does a closure keep access to local variables of its outer function even after the outer function returns?
  3. In the example above, what does calling next() multiple times do?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.