When would you use Function Signatures in a real project
Fast recall
Quick revision
Core answer
Practical understanding of Function Signatures.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
Executed — the canonical counter:
func makeCounter() func() int {
count := 0
return func() int {
count++ // captures count — from the ENCLOSING scope
return count
}
}
counter := makeCounter()
counter() // 1
counter() // 2
counter() // 3 — state persists across callsmakeCounter returned, but count didn't die — the inner function CLOSED OVER it. Each call to the closure reads and writes the SAME count variable. That's the definition: a function + the captured environment it references.
What capture means mechanically: Go closures capture by REFERENCE — the inner function holds a pointer to the variable, not a copy of its value at creation. Writes inside the closure are visible outside (if the outer scope still holds a reference) and vice versa. Two closures created from the same scope share the same captured variables.
When would you use Function Signatures in a real project
Direct Answer
A function value that captures variables from its enclosing scope. The captured variables stay alive (and writable) after the outer function returns. Closures give function values state.
Deep Dive & Architecture
The classic interview demonstration — shared state:
func makePair() (func() int, func(int)) {
n := 0
return func() int { return n }, func(v int) { n = v }
}
get, set := makePair()
set(42)
get() // 42 — the getter sees the setter's write
One variable, two closures — both see the same n. The pattern generalizes: getters/setters, iterators (the closure holds the loop position), memoization (the closure holds the cache).
What closures are NOT: classes (no methods, no inheritance — just a function with captured state); generators (Go's generators are channels or callback-passing — but the ITERATION state a generator would hold, a closure can); or a performance feature (the capture is a pointer indirection — closures in hot loops are measurable).
The everyday uses: callbacks with context (handler closures capturing a request variable), the error-wrapped deferred closures (the defer topic's pattern), and function values generally (every func value in Go that references its scope IS a closure — there's no separate 'closure type').
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Function Signatures, and when would you use it?
- How would you compare Function Signatures with an alternative?
- What is a common mistake when using Function Signatures?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.