Go init() Functions 🎯

beginner
19 min

Go init() Functions 🎯

Welcome to our deep dive into Go init() Functions! In this lesson, we'll explore how init() functions help you ensure that your Go programs run smoothly and efficiently. We'll start from the basics and gradually move towards more advanced examples. Let's get started!

What are init() Functions? 📝

In Go, init() functions are special functions that are automatically called when a package is imported or a variable is accessed for the first time within that package. These functions help you perform some setup work before your code runs.

go
package main import "fmt" var x int func init() { x = 10 } func main() { fmt.Println(x) }

In the above example, the init() function assigns the value 10 to the variable x. When you run the program, it will output 10.

Why use init() Functions? 💡

Init functions are useful for initializing variables with complex calculations, loading data from files, or connecting to external resources before your main function starts executing. They help keep your code organized and avoid unnecessary initializations.

init() Function Types 📝

Go supports two types of init functions:

  1. Package-level init functions: These are associated with the entire package and are called before the main function.
  2. Non-package level init functions: These are associated with a specific variable or constant and are called when the variable or constant is first accessed.

When are init() Functions Called? 💡

Init functions are called in the following order:

  1. All package-level init functions are called in the order they are declared within the package.
  2. If a package imports another package, the init functions of the imported package are called before the init functions of the importing package.
  3. Non-package level init functions are called when the variable or constant they are associated with is first accessed.

Quiz 🎯

Quick Quiz
Question 1 of 1

In which order are init functions called in Go?

Best Practices 💡

  • Keep init functions simple and focused on a single task.
  • Avoid long-running init functions as they can delay the execution of your program.
  • Consider using defer statements for long-running tasks instead of init functions.

Conclusion ✅

In this lesson, we learned about Go's init() functions, their purpose, types, and calling order. Init functions help you set up your programs efficiently and keep your code organized. Happy coding! 🎈

Stay tuned for more in-depth lessons on Go!