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.1k Golang : Random Rune generator
+16.6k Golang : Simple client server example
+18.8k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+17.4k Golang : Get path name to current directory or folder
+30.7k Golang : Validate email address with regular expression
+10.6k Golang : flag provided but not defined error
+8.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+5.1k PHP : How to check if an array is empty ?
+15.6k Golang : How to generate QR codes?
+8.1k Golang : Serving HTTP and Websocket from different ports in a program example
+14k Golang : How to get Unix file descriptor for console and file
+5.5k WARNING: UNPROTECTED PRIVATE KEY FILE! error message