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.1k Golang : Test input string for unicode example
+19.8k Golang : Check if os.Stdin input data is piped or from terminal
+9k Golang : Generate EAN barcode
+13.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+12k Golang : How to display image file or expose CSS, JS files from localhost?
+11.1k Golang : Delay or limit HTTP requests example
+6k Golang & Javascript : How to save cropped image to file on server
+17.8k Golang : Check if a directory exist or not
+5.1k Unix/Linux : How to archive and compress entire directory ?
+5.8k Golang : Measure execution time for a function
+9.1k Golang : Web(Javascript) to server-side websocket example