Golang : Defer function inside init()
Putting this short note down for those intending to use defer function inside init(). IF you put a defer function inside the init() block, the deferred function will be executed regardless and not deferred. This is because the init() function role is to repair correctness or prepare the environment variables within the source file before executing other function or to be precise... the main() function block.
From the official documentation, https://golang.org/doc/effective_go.html#init :
"a common use of init functions is to verify or repair correctness of the program state before real execution begins."
The keyword is BEFORE
Reference :
See also : Golang : When to use init() function?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+36.1k Golang : Get file last modified date and time
+6.6k Golang : Totalize or add-up an array or slice example
+5k JQuery : Calling a function inside Jquery(document) block
+14.3k Golang : Chunk split or divide a string into smaller chunk example
+22.3k Golang : Securing password with salt
+11.2k Golang : Fix go.exe is not compatible with the version of Windows you're running
+29.2k Golang : missing Git command
+7.9k Swift : Convert (cast) String to Double
+20.2k Golang : Reset or rewind io.Reader or io.Writer
+8.5k PHP : How to parse ElasticSearch JSON ?
+6k Linux/MacOSX : Search for files by filename and extension with find command
+17.6k Golang : Clone with pointer and modify value