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
+12.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+4.3k Golang : micron to centimeter example
+9.4k Golang : Wait and sync.WaitGroup example
+17.4k Golang : How to get hour, minute, second from time?
+8k Golang : Get final balance from bit coin address example
+15.2k Golang : convert string or integer to big.Int type
+10.9k Golang : Gorilla web tool kit secure cookie example
+46k Golang : Convert int to byte array([]byte)
+5.9k Golang : Warp text string by number of characters or runes example
+31.6k Golang : How to check if a date is within certain range?
+17.4k Golang : Display list of time zones with GMT
+5k Cash Flow : 50 days to pay your credit card debt