🐹 Go (Golang) Intermediate

What is a closure in Go?

Answer

A closure is a function value that captures and carries references to variables from its enclosing scope. In Go, functions are first-class values — they can be assigned to variables, passed as arguments, and returned from functions. A closure "closes over" the variables it references: func counter() func() int { n := 0; return func() int { n++; return n } }. Each call to counter() creates a new n with its own closure. A common pitfall in loops: all goroutines in a loop may share the same loop variable unless it is passed as an argument or a local copy is made.