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
+24.1k Golang : Find biggest/largest number in array
+12.5k Golang : Encrypt and decrypt data with x509 crypto
+28k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+5.8k Get website traffic ranking with Similar Web or Alexa
+5.4k Golang : Intercept, inject and replay HTTP traffics from web server
+7.2k Golang : Get Alexa ranking data example
+8.9k Golang : Get final balance from bit coin address example
+12.7k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+8.3k Golang : HttpRouter multiplexer routing example
+7.4k Golang : File system scanning
+7.7k Javascript : Push notifications to browser with Push.js
+11.7k Golang : Convert(cast) float to int