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.4k Python : Convert(cast) string to bytes example
+10.1k Golang : Read file and convert content to string
+51.5k Golang : Check if item is in slice/array
+5.9k Golang : List all packages and search for certain package
+12.4k Golang : Display list of countries and ISO codes
+14.1k Golang : Human readable time elapsed format such as 5 days ago
+14.6k Golang : How to pass map to html template and access the map's elements
+16.2k Golang : Get sub string example
+27.4k Golang : Find files by name - cross platform example
+14.7k Golang : How to get URL port?
+5.7k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+15.2k Golang : How do I get the local IP (non-loopback) address ?