Sobes.tech
Junior — Middle

What behavior will an anonymous function declared inside a loop with defer exhibit at the end of each iteration?

sobes.tech AI

Answer from AI

If an anonymous function using defer is declared inside a loop, then calls to these deferred functions are not executed immediately, but are accumulated and will be called only after exiting the function that contains the loop.

This means that all deferred calls inside the loop will be executed in reverse order after the entire function finishes, not after each iteration.

Example:

for i := 0; i < 3; i++ {
    defer fmt.Println(i)
}
// When exiting the function, the output will be:
// 2
// 1
// 0

If you want the deferred function to execute at the end of each iteration, avoid using defer inside the loop.

What behavior will an anonymous function declared… - sobes.tech