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.5k Golang : Gorrila set route name and get the current route name
+7.2k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.6k Golang : How to handle file size larger than available memory panic issue
+32.6k Golang : Copy directory - including sub-directories and files
+33.8k Golang : All update packages with go get command
+25.2k Golang : Create PDF file from HTML file
+6.5k CodeIgniter : form input set_value cause " to become & quot
+36.6k Golang : How to split or chunking a file to smaller pieces?
+9.2k Golang : Gonum standard normal random numbers example
+9k Golang : GMail API create and send draft with simple upload attachment example
+5.6k Golang : If else example and common mistake
+5.9k Golang : Markov chains to predict probability of next state example