Written by
Jimmy John
on
on
Defer on exit
Working with go, sometimes you may want to run a deferred action on Exit. Something like:
|
|
In the above code, World
will never get printed. This is because defer
is not run on os.Exit
.
One pattern to fix this is to have main call another function that does the real work. Defer on that function will work e.g.
|
|
The above snipper correctly prints:
Hello
World
You can see real world usage of this pattern in Packer