0
0
Goprogramming~5 mins

Module initialization in Go

Choose your learning style9 modes available
Introduction
Module initialization helps set up things before your program starts running main code. It prepares data or settings automatically.
When you want to set default values before your program runs.
When you need to prepare resources like database connections at the start.
When you want to register something automatically without calling it manually.
When you want to check or validate something once before main code runs.
Syntax
Go
func init() {
    // code to run before main
}
The init function runs automatically before main starts.
You can have multiple init functions in one package; they run in the order they appear.
Examples
This example shows init running first, printing a message before main.
Go
package main

import "fmt"

func init() {
    fmt.Println("Setup before main")
}

func main() {
    fmt.Println("Main function runs")
}
Multiple init functions run in the order they appear.
Go
package main

import "fmt"

func init() {
    fmt.Println("First init")
}

func init() {
    fmt.Println("Second init")
}

func main() {
    fmt.Println("Main runs")
}
Sample Program
This program shows how init runs before main automatically.
Go
package main

import "fmt"

func init() {
    fmt.Println("Initializing module")
}

func main() {
    fmt.Println("Program started")
}
OutputSuccess
Important Notes
init functions cannot take parameters or return values.
init runs once per package before main or before the package is used.
Use init for setup only; avoid complex logic to keep code clear.
Summary
init functions run automatically before main starts.
Use init to prepare or set up things your program needs.
You can have many init functions; they run in the order they appear.