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
+9.2k Golang : Convert(cast) string to int64
+6.3k Golang : Convert an executable file into []byte example
+4.6k Which content-type(MIME type) to use for JSON data
+7.9k Golang : Tell color name with OpenCV example
+11.4k Golang : Gorilla web tool kit secure cookie example
+4.7k Nginx and PageSpeed build from source CentOS example
+21.4k Golang : Convert string slice to struct and access with reflect example
+34.3k Golang : Smarter Error Handling with strings.Contains()
+18.1k Golang : Aligning strings to right, left and center with fill example
+10.1k Golang : Convert file content to Hex
+29.2k Golang : Login(Authenticate) with Facebook example
+13.4k Golang : Query string with space symbol %20 in between