What is init function in Go: Explanation and Example
init function is a special function that runs automatically before the main program starts. It is used to set up or initialize things like variables or configurations without being called explicitly.How It Works
The init function in Go is like a setup helper that runs by itself before your program's main code begins. Imagine you are preparing ingredients before cooking a meal; the init function prepares everything needed so the main cooking (your program) can run smoothly.
Every Go package can have one or more init functions. When you run your program, Go automatically calls all these init functions in the order of package dependencies, before the main function starts. You never call init yourself; Go does it for you.
Example
This example shows how the init function sets up a variable before the main function uses it.
package main import "fmt" var message string func init() { message = "Hello from init!" } func main() { fmt.Println(message) }
When to Use
Use the init function when you need to prepare or configure something before your program runs. For example, you can use it to:
- Initialize package-level variables
- Set up connections like databases or files
- Register types or plugins automatically
This helps keep your main function clean and focused on the main logic.
Key Points
- The
initfunction runs automatically beforemain. - You cannot call
initmanually. - Each package can have multiple
initfunctions. - Use
initto set up initial state or configuration.