In Go, the init function is a special function primarily used for initializing package-level variables or executing specific setup tasks. Each package can contain multiple init functions, which are automatically executed in the order they appear in the code and are called before the main function of the program.
init Function's Primary Uses:
- Initialize package-level variables: If a package contains complex variables requiring initialization via a function, the
initfunction is the ideal location for this. - Perform pre-startup checks or configurations: For example, verifying environment variables are set or initializing database connections.
- Registration: In certain cases, a package may need to register its capabilities or services into a global lookup table, and the
initfunction can be used for such registration.
Example
Suppose we have a package for a web service that needs to ensure the database connection is ready before startup and configure internal parameters based on environment variables. We can use the init function to accomplish these tasks:
gopackage database import ( "database/sql" "log" "os" ) var db *sql.DB func init() { var err error db, err = sql.Open("postgres", os.Getenv("DATABASE_URL")) if err != nil { log.Fatalf("Error opening database: %v", err) } // Additional initialization settings can be added here, such as database migrations. } // GetDB is a function that returns the database connection. func GetDB() *sql.DB { return db }
In this example, the init function ensures the database connection is properly initialized before the package is imported and used by other code. Thus, other parts of the code calling GetDB() can safely assume the database connection is valid without concerns about nil or uninitialized values.
Summary
The init function provides a convenient way to set up package-level state or execute initialization tasks, which helps modularize code and establish clear startup logic. However, using the init function requires caution, as its execution order and timing may affect program behavior, especially when multiple packages have dependencies.