0
0
GoConceptBeginner · 3 min read

What is Closure in Go: Simple Explanation and Example

In Go, a closure is a function value that references variables from outside its own body. It 'closes over' these variables, keeping their state even after the outer function has finished running.
⚙️

How It Works

Think of a closure like a backpack that a function carries around. This backpack holds variables from the place where the function was created, not just inside the function itself. Even if the original place where those variables lived is gone, the function still has access to them inside its backpack.

In Go, when you create a function inside another function, the inner function can use variables from the outer function. The inner function remembers these variables and can change or use them later. This is useful because it lets the inner function keep track of information between calls, like a counter or a setting.

💻

Example

This example shows a function that returns another function. The returned function remembers the variable count and increases it each time it is called.

go
package main

import "fmt"

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    c := counter()
    fmt.Println(c()) // 1
    fmt.Println(c()) // 2
    fmt.Println(c()) // 3
}
Output
1 2 3
🎯

When to Use

Closures are great when you want to keep some data private but still use it across multiple function calls. For example, you can use closures to create counters, generate unique IDs, or manage state in a clean way without using global variables.

They are also useful in event handling, callbacks, or when you want to customize behavior by creating functions that remember specific settings or data.

Key Points

  • A closure is a function that remembers variables from its creation context.
  • It allows functions to have private state that persists between calls.
  • Closures help avoid global variables and keep code organized.
  • They are useful for counters, callbacks, and managing state.

Key Takeaways

A closure in Go is a function that captures and remembers variables from its surrounding scope.
Closures let you keep state between function calls without using global variables.
Use closures for counters, unique ID generators, and managing private data.
Closures help write cleaner and more modular code by encapsulating behavior and data.