SoFunction
Updated on 2025-03-02

Go language init function

The init function will be executed before the main function is executed, and init is used to set packages, initialize variables, or other boot work that must be completed first before the program runs.

For example: When registering a database driver.

There is an init function here

package postgres

package postgres
import (
    "database/sql"
    "database/sql/driver"
    "errors"
)
// PostgresDriver provides our implementation for the
// sql package.
type PostgresDriver struct{}
// Open provides a connection to the database.
func (dr PostgresDriver) Open(string) (, error) {
    return nil, ("Unimplemented")
}
var d *PostgresDriver
// init is called prior to main.
func init() {
    d = new(PostgresDriver)
    ("postgres", d)
}

Here is the main function

// Sample program to show how to show you how to briefly work
// with the sql package.
package main

import (
    "database/sql"

    _ "/goinaction/code/chapter3/dbdriver/postgres"
)

// main is the entry point for the application.
func main() {
    ("postgres", "mydb")
}

You can see that the main function is used here, thanks to the init function above

_ "/goinaction/code/chapter3/dbdriver/postgres"

The function of underscore plus the package name is to execute the init function of this package.

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.