How golang’s “defer” capture closure’s parameter?

The ‘part 2’ closure captures the variable ‘i’. When the code in the closure (later) executes, the variable ‘i’ has the value which it had in the last iteration of the range statement, ie. ‘4’. Hence the

4 4 4 4 4

part of the output.

The ‘part 3’ doesn’t capture any outer variables in its closure. As the specs say:

Each time the “defer” statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

So each of the defered function calls has a different value of the ‘n’ parameter. It is the value of the ‘i’ variable in the moment the defer statement was executed. Hence the

4 3 2 1 0

part of the output because:

… deferred calls are executed in LIFO order immediately before the surrounding function returns …


The key point to note is that the ‘f()’ in ‘defer f()’ is not executed when the defer statement executes

but

the expression ‘e’ in ‘defer f(e)’ is evaluated when the defer statement executes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)