0
0
GoHow-ToBeginner · 3 min read

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 init manually (it is called automatically by Go).
  • Using init for complex logic that should be in main or other functions.
  • Having multiple init functions 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

FeatureDescription
Function nameMust be exactly init
ParametersNone allowed
Return valuesNone allowed
CallAutomatically by Go runtime
PurposePackage initialization before main
Multiple initAllowed 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.