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
+7.4k Golang : Shuffle strings array
+21k Golang : Create and resolve(read) symbolic links
+7.4k Golang : Rename part of filename
+9.1k Golang : Write multiple lines or divide string into multiple lines
+8.7k Golang : Accept any number of function arguments with three dots(...)
+12.5k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+13.1k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+6.7k Swift : substringWithRange() function example
+8.6k Golang : Find duplicate files with filepath.Walk
+11.8k Golang : Convert(cast) bigint to string
+14.6k Golang : Normalize unicode strings for comparison purpose
+8.2k Golang : Count leading or ending zeros(any item of interest) example