Skip to content

Latest commit

 

History

History
57 lines (37 loc) · 1.21 KB

4.4.md

File metadata and controls

57 lines (37 loc) · 1.21 KB

init()

Concepts

Every package can have an init() function. For non-main packages, init() is run when the package is imported. For main, init() is run before main() begins.

This is often used to initialize any variables or external network connections needed.

package main

import "fmt"

var (
    a int
    b string
)
func init() {
    a = 4
    fmt.Println("1. Initialized")
}

func main() {
    b = "hello"
    fmt.Println("2. Started")
    fmt.Println(a, b)
}

Sometimes, you would like to run the init function from a package, but don't intend to use any exported names in the package:

package main

import _ "github.com/user/project/pkg/example"

func main() {
    ...
}

Importing a package without using it in go is an error. Including the _ before the import path tells the go compiler that no exported names are going to be used.

Exercises

Tips

  • You can have multiple init() functions in the same file. They will be called in order.

Further Reading

Want to know the deep ins an outs of package initialization? This is a great article.


prev -- up -- next