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
+6.3k Golang : Create new color from command line parameters
+6.7k PHP : Shuffle to display different content or advertisement
+8.7k Golang : Generate Datamatrix barcode
+10.5k Golang : Generate random integer or float number
+17.2k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+16.2k Golang : Get sub string example
+34.2k Golang : Proper way to set function argument default value
+6.9k Golang : Find the longest line of text example
+5.6k Golang : Get S3 or CloudFront object or file information
+17.4k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+27.1k Golang : Force your program to run with root permissions
+12.9k Golang : Remove or trim extra comma from CSV