How to Use init Function in Go: Syntax and Examples
In Go, the
init function is a special function that runs automatically before the main function or when a package is imported. It is used to set up initial state or perform setup tasks without being called explicitly.Syntax
The init function has no parameters and no return values. You can define one or more init functions per package or file. The Go runtime calls all init functions automatically in the order they appear.
- func init(): Declares the init function.
- No parameters or return values allowed.
- Multiple init functions can exist in the same package.
go
func init() {
// initialization code here
}Example
This example shows how the init function runs before main to initialize a package-level variable.
go
package main import "fmt" var message string func init() { message = "Hello from init!" fmt.Println("init function called") } func main() { fmt.Println("main function called") fmt.Println(message) }
Output
init function called
main function called
Hello from init!
Common Pitfalls
Common mistakes when using init include:
- Trying to call
initmanually (it is called automatically by Go). - Using
initfor complex logic that should be inmainor other functions. - Having multiple
initfunctions in many files can make code harder to follow.
Keep init simple and focused on setup tasks.
go
package main import "fmt" // Wrong: calling init manually func init() { fmt.Println("init called") } func main() { // init() // This is allowed but discouraged; it won't cause a compile error but is not recommended fmt.Println("main called") }
Output
init called
main called
Quick Reference
| Feature | Description |
|---|---|
| Function name | Must be exactly init |
| Parameters | None allowed |
| Return values | None allowed |
| Call | Automatically by Go runtime |
| Purpose | Package initialization before main |
| Multiple init | Allowed in same package or file |
Key Takeaways
The init function runs automatically before main and is used for setup.
You cannot call init manually or give it parameters or return values.
Multiple init functions can exist and run in file order.
Keep init simple to avoid confusing code flow.
Use init to initialize package-level variables or state.