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!
More Related questions...