In Go, the init function serves a specific purpose. Each package can contain one or more init functions, which are automatically called when the program starts for initialization tasks. The main characteristics of the init function include:
-
Automatic Execution: The
initfunction is automatically invoked at the package level without manual intervention. It executes after all variable declarations within the package and before the program'smainfunction. -
Initialization of Package Variables: It is commonly used for initializing complex variables that cannot be directly initialized through declarations.
-
Multiple
initFunctions: A package can define multipleinitfunctions, which are executed in the order they appear in the code. -
Cross-Package Execution Order: If a package imports other packages, the
initfunctions of the imported packages execute before the importing package. This ensures that the current package's initialization logic proceeds correctly after dependencies are properly initialized.
Example
Suppose we have a package that needs to load configuration files and establish a database connection at startup. We can use the init function to handle these initialization tasks.
gopackage mypackage import ( "database/sql" "log" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func init() { var err error db, err = sql.Open("mysql", "user:password@/dbname") if err != nil { log.Fatalf("Error opening database: %v", err) } // You can load other resources requiring initialization here } func main() { // In the main function, db is ready for use }
In this example, the init function opens the database connection and assigns the connection object to the global variable db. This allows other parts of the program to directly use db for database operations without concerns about uninitialized connections.
In summary, the init function provides a powerful and flexible mechanism for package initialization in Go, making program startup and configuration safer and more seamless.