Golang / GoLang Basics Interview Questions
What are closures in Go and what is the loop variable capture gotcha?
A closure is a function that references and closes over variables from its surrounding scope. The closure captures the variable itself — not a copy of its value at the moment of creation. This distinction is the source of one of the most common Go bugs.
// Closure capturing outer variable
func makeCounter() func() int {
count := 0
return func() int {
count++ // captures 'count' — reads its current value each call
return count
}
}
c := makeCounter()
fmt.Println(c(), c(), c()) // 1 2 3
c2 := makeCounter() // independent counter
fmt.Println(c2()) // 1 (fresh)
// CLASSIC GOTCHA: loop variable capture
funcs := make([]func(), 3)
for i := 0; i < 3; i++ {
funcs[i] = func() { fmt.Println(i) } // captures &i, not a copy!
}
funcs[0]() // prints 3 (not 0!)
funcs[1]() // prints 3
funcs[2]() // prints 3
// By the time any func runs, the loop ended and i == 3
// FIX 1: pass i as an argument (creates a per-iteration copy)
for i := 0; i < 3; i++ {
go func(n int) { fmt.Println(n) }(i) // n is a copy of i
}
// FIX 2: shadow i with a new variable per iteration
for i := 0; i < 3; i++ {
i := i // new 'i' that belongs to this iteration
funcs[i] = func() { fmt.Println(i) }
}
// Go 1.22+: loop variables are per-iteration by default — bug gone!
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
