Programming Languages - Closures

Last Updated: 2023-02-23

Closures are special functions that can capture the environment, i.e. variables within a lexical scope.

Or "an inner function that has access to the outer function’s variables".

closure = a function + context (free variables)

Free variables are used inside the function but defined in the context (enclosing scope), NOT passed to functions as parameters.

A callback using context variables is a closure.


"closures" = lambda expressions.

Closures are to lambdas as objects are to classes (lambda:closure = class:instance): closures and instances are runtime only; lambdas occupy no data memory at runtime but may occupy code memory, closures occupy data memory but not code memory.

In other languages like Python, closure is unrelated to Lambdas.


Example from the official website: https://go.dev/tour/moretypes/25

func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
  • sum is defined outside of the returned func.
  • the returned func reads and updates the value of sum
func main() {
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {

In the main function, pos and neg each has their own sum, the sum is set to 0 when created (pos := adder()) and the value of sum will be updated in the loop.


Closures can be used to emulate private methods as in other languages: they 'remember' the data and you can later operate on the data through the returned functions.