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
+5.8k Unix/Linux/MacOSx : Get local IP address
+5.5k Golang : Return multiple values from function
+6.7k Unix/Linux : How to get own IP address ?
+11.3k Google Maps URL parameters configuration
+10.6k Generate Random number with math/rand in Go
+14.2k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+16.3k Golang : How to check if input from os.Args is integer?
+27.9k PHP : Convert(cast) string to bigInt
+20.4k Golang : Compare floating-point numbers
+18.6k Golang : Write file with io.WriteString
+10.3k Golang : Get login name from environment and prompt for password
+7.3k Javascript : How to get JSON data from another website with JQuery or Ajax ?