Knaph

Packages, Modules, and Testing58 of 62

Defer Order

Inside the loop in run, defer a function that appends i to the named return value order — remember to pass i in as a parameter to the deferred closure (defer func(i int) { ... }(i)) so each deferred call captures its own value instead of the loop variable. Since deferred calls run last-in-first-out, the printed order will be the reverse of 1..n.

Sign in to try this exercise.