Closures

A closure is a function that remembers the variables around it, even after the outer function has finished.

The idea

Imagine handing someone a sealed envelope with a calculator inside that also has a tiny notepad attached. Each time they press “+1” it updates its own notepad. Give a second envelope to someone else and they get a second, separate notepad.

In Go a function literal can use variables from the function that created it. Those variables are kept alive for as long as the closure exists. Each call to counter() creates a new variable n, so every closure counts independently.

Watch it work

Try it

Common mistakes