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
+15.1k Golang : Login and logout a user after password verification and redirect example
+9.5k Golang : Post data with url.Values{}
+11.5k Golang : Gin framework accept query string by post request example
+11.6k Golang : Get uploaded file name or access uploaded files
+6.4k Android Studio : Indicate progression with ProgressBar example
+18.9k Golang : How to get time zone and load different time zone?
+11.6k Android Studio : Use image as AlertDialog title with custom layout example
+16.8k Golang : Check if directory exist and create if does not exist
+17.2k Golang : Underscore or snake_case to camel case example
+19.5k Golang : Convert Unix timestamp to UTC timestamp
+7.9k Golang : Test a slice of integers for odd and even numbers
+8.2k JavaScript/JQuery : Detect or intercept enter key pressed example