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
+7.1k Golang : Takes a plural word and makes it singular
+34.1k Golang : Proper way to set function argument default value
+11.3k CodeIgniter : How to check if a session exist in PHP?
+11.7k Get form post value in Go
+29.5k Golang : JQuery AJAX post data to server and send data back to client example
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+5.3k Responsive Google Adsense
+8.9k Golang : Random integer with rand.Seed() within a given range
+13.2k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.9k Unix/Linux : How to test user agents blocked successfully ?
+25.8k Golang : How to write CSV data to file
+7.9k Golang : Lock executable to a specific machine with unique hash of the machine