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
+14.1k Android Studio : Use image as AlertDialog title with custom layout example
+20.9k Golang : Sort and reverse sort a slice of strings
+29.5k Golang : Get and Set User-Agent examples
+16.6k Golang : Set up source IP address before making HTTP request
+29k Golang : JQuery AJAX post data to server and send data back to client example
+41.2k Golang : Convert string to array/slice
+5.1k Python : Convert(cast) string to bytes example
+10.9k Google Maps URL parameters configuration
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+9.2k Golang : Terminate-stay-resident or daemonize your program?
+31.8k Golang : Validate email address with regular expression
+19.9k Golang : How to get struct tag and use field name to retrieve data?