What are closures in Go?

Updated Apr 28, 2026

Short answer

A closure is an anonymous function that references variables from outside its own body (lexical scope).

Deep explanation

The function may access and assign to the referenced variables; in this sense the function is 'bound' to the variables. The Go runtime allocates these captured variables on the heap if they escape the scope, ensuring they outlive the outer function.

Real-world example

Creating middleware in an HTTP server where the outer function takes a configuration object and returns the actual HTTP handler function bound to that configuration.

Common mistakes

  • Capturing loop variables in goroutines incorrectly (prior to Go 1.22), leading to all goroutines pointing to the same final loop iteration value.

Follow-up questions

  • How did Go 1.22 fix the loop variable capture issue?

More Golang interview questions

View all →