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
+6k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+6.3k Golang : Selection sort example
+4.9k Golang : micron to centimeter example
+13.3k Golang : Read from buffered reader until specific number of bytes
+6.8k Fix sudo yum hang problem with no output or error messages
+15.9k Golang : Get file permission
+33.7k Golang : convert(cast) bytes to string
+6.1k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+7.9k Javascript : Put image into Chrome browser's console
+19.4k Golang : How to Set or Add Header http.ResponseWriter?