main and init
main is the function the runtime calls to start an executable. init is a package-level function that runs automatically before main, once per package, in import order.
Detailed Explanation
An executable in Go is a package main that defines func main(). When you run the binary, the runtime initializes the imported packages, then calls main. There are no command-line arguments on main itself — you read os.Args or use the flag package inside it. main takes no parameters and returns nothing. To exit with a status code, call os.Exit, knowing that os.Exit skips deferred calls in main.
init exists for registration, not for business logic. You may write func init() { ... } in any file. A package can have several init functions, even several in one file. The compiler concatenates them in file-name order, then source order. You never call init yourself; there is no way to pass it arguments or get a return value.
Startup order is deterministic. For the main package, Go first initializes each imported package (recursively), then the main package's package-level variables, then its init functions, then main. Inside a package, variables are initialized in dependency order, then init runs. Blank imports exist so you can pull in a package solely for its init — database/sql drivers register themselves this way.
Prefer explicit setup over init. An init that opens a database, reads a config file, or dials the network makes the package hard to test and hard to start twice. A NewServer(cfg Config) (*Server, error) call from main does the same work, surfaces the error, and lets tests pass a fake. Reach for init when you are registering a value in a global table (an SQL driver, an image format, a pprof handler) and the registration has no configuration.
Package-level variables run first. var db = mustOpen() executes during initialization, before any init in that package. A panic there crashes the process during startup with a stack that mentions init even if you never wrote an init function.
What it costs. init work is paid on every process start, including go test for packages that import yours. Heavy init slows tests and hides failures until process launch. main that does too much is a different problem: keep it as a thin wiring function that parses flags, builds dependencies, and blocks on ListenAndServe or errgroup.Wait.
Code Examples
package main
import (
"fmt"
"os"
)
func init() {
// Runs before main, after imported packages have initialized.
fmt.Println("init")
}
func main() {
fmt.Println("main", os.Args[0])
}
// Output:
// init
// main /tmp/progDriver-style registration: the blank import exists for init side effects.
// Driver-style registration: the blank import exists for init side effects.
package main
import (
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib"
)
func open() (*sql.DB, error) {
// pgx registered itself with database/sql during its init.
return sql.Open("pgx", "postgres://localhost/shop")
}Prefer a constructor you can call from tests over hidden init work.
// Prefer a constructor you can call from tests over hidden init work.
func NewServer(addr string) *Server {
return &Server{addr: addr}
}
type Server struct{ addr string }Common Gotchas
`os.Exit` skips defers in `main`
`defer f.Close(); os.Exit(1)` never closes the file. Return from `main` after setting a status via a helper, or defer cleanup in a function that `main` calls before `os.Exit`.
`init` cannot return an error
a failed config load inside `init` can only log or `panic`. Move fallible startup into `main` so you can exit with a message.
Several `init` functions are easy to lose track of
they run in file-name order across the package. A new file named `aaa.go` can change startup order. Keep at most one `init` per package unless you are registering independent types.
Tests run `init` too
importing a package in a test executes its `init`. If that `init` dials the network, every unit test pays for it.