Golang : When to use init() function?
When to use init()
function? If you read this official documentation at effective go init, it can be confusing for new comers to Golang.
To explain when to use init()
in the simplest term possible... you can try to think of what you need to do before launching your Go or other programs.
For example, in order for a program to execute properly in a Unix/Linux or Windows environment, you need to setup the environment variables first. Environment variables such as token, username, password, directories that are stored in the memory and retrieved by your program during execution. After the environment variables are properly configured, then your program can execute smoothly.
init()
is similar to setting up environment variables, except that it takes place inside your code. The values or states that are initialize will affect the codes behaviour until the values or states are override somewhere during execution. Hence, according to the official document - [a common use of init functions is to verify or repair correctness of the program state]
For example, in order for image package At()
and Decode()
to function properly. You need to init
the image.RegisterFormat()
function first.
Why?
Otherwise, image does not know what to expect. Is image's At()
or Decode()
functions going to deal with jpeg, gif or png files? Without the init()
, your program will throw out panic information. Which, I wish Golang will provide more description on what is causing the error rather than just throwing out panic stack information in future.
See more at https://www.socketloop.com/tutorials/golang-how-to-read-jpg-jpeg-gif-and-png-files
Another usage of init()
function is to create a default behaviour for your own program. For example, if your program extract from the environment variables and assign the values to the your own variable. If the username == '' then do what. For example, this will cause your program to exit with the message $USERNAME not set.
func init() {
if username == "" {
log.Fatal("$USERNAME not set")
}
}
So, is init()
function limited to the same file as where main()
function reside? No, you can place one init()
function in each source file.
Reference :
See also : Golang : Set, Get and List environment variables
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
+12.1k Golang : Exit, terminating or aborting a program
+7.1k Golang : How to stop user from directly running an executable file?
+7k Golang : Process json data with Jason package
+19.1k Golang : How to Set or Add Header http.ResponseWriter?
+25.3k Golang : How to write CSV data to file
+10.9k Android Studio : Create custom icons for your application example
+6.2k Golang : Calculate diameter, circumference, area, sphere surface and volume
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+9.1k Golang : Convert(cast) string to int64
+9.2k Golang : Validate IPv6 example
+7.1k Golang : How to handle file size larger than available memory panic issue
+17.5k Golang : Put UTF8 text on OpenCV video capture image frame