Rez Moss

Rez Moss

Personal Musings: A Blog for the Tech-Savvy and Curious Mind

Go's init() Function: Uses and Best Practices

Mar 2021

The init() function in Go is a special function that’s automatically executed before the main() function. It serves as a mechanism for performing one-time initialization tasks. Here’s what you need to know about init():

Key Characteristics

  • Each package can have multiple init() functions.
  • They’re called in the order they’re defined within a file.
  • Across files in a package, they’re called in lexical file name order.
  • init() functions are executed after all variable declarations in the package have evaluated their initializers.

Common Uses

  1. Setting up global variables that can’t be initialized in a single assignment.
  2. Registering with other packages or services.
  3. Performing one-time computations or data structure setup.
  4. Verifying or repairing program state before execution begins.

Considerations

  1. Keep init() functions simple and fast to avoid slowing down program startup.
  2. Avoid side effects or depending on other packages’ initialization order.
  3. Use init() sparingly; prefer explicit initialization when possible.
  4. Don’t rely on init() for critical functionality, as it makes testing harder.
  5. If using multiple init() functions, ensure they’re independent of each other.

Important Notes

  • init() functions can’t be referenced or called explicitly.
  • They’re guaranteed to run only once, even if the package is imported multiple times.
  • init() functions have no parameters and return no values.

Example

var globalCache map[string]string

func init() {
    globalCache = make(map[string]string)
    // Perform any other one-time setup
}

func main() {
    // globalCache is now initialized and ready to use
}

Remember, while init() functions are powerful, they should be used judiciously. In many cases, explicit initialization in main() or in a dedicated setup function can lead to clearer and more maintainable code.