The init function in Go has special significance. It is automatically executed after the package-level variables are initialized, but before any other function is called. Specifically, the execution timing of the init function is as follows:
- When a package is imported, the Go compiler first checks if it has been initialized. If not, it initializes the dependencies of the package.
- Then, after the package-level variables are initialized, the init function for the package is called. This process is automatic and determined at compile time.
- If a package has multiple init functions (which may be scattered across multiple files in the package), they are called in the order they appear in the code.
- If a package is imported by multiple other packages, its init function is executed only once.
This mechanism ensures that the init function runs only once, regardless of how many times the package is imported, and before the main function of the program runs. This design is used for performing initialization tasks such as setting up internal data structures of the package, initializing variables, or registering necessary information.
For example, if there is a database package, you might set up the database connection pool in the init function:
gopackage database import "database/sql" var dbPool *sql.DB func init() { var err error dbPool, err = sql.Open("postgres", "connection_string") if err != nil { log.Fatalf("Database connection failed: %s", err) } } // Other database operation functions...
In this example, regardless of how many times the database package is imported or where it is imported in the program, the init function ensures that the database connection is set up before any database operations are performed.
