π§ Class 19: Init Function
Video Topic: init()
Function in Go
π€ Code Written in This Class
//example 1
package main
import "fmt"
func main() {
fmt.Println("Hello Init Function!")
}
func init() {
fmt.Println("I am the function that is executed first")
}
//example 2
package main
import "fmt"
var a = 10
func main() {
fmt.Println(a)
}
func init() {
fmt.Println(a)
a = 20
}
π Key Concepts
-
init()
is a special Go function that runs beforemain()
, automatically. -
You can have multiple
init()
functions across different files and packages. They all run in the order of:-
Dependency packages first
-
File order (top to bottom) next
-
-
You don't call
init()
manually. It runs automatically before the program starts.
π§ CLI Memory & Execution Visualization (example 1)
Letβs visualize how Go handles init()
under the hood:
// π Compile Time: Go detects init()
Found init() in main package β
----------- EXECUTION BEGINS -----------
π§ Data Segment:
(none)
π Stack:
ββββββββββββββββββββββ
β π§© init() β
ββββββββββββββββββββββ
π¨οΈ Output:
"I am the function that is executed first"
π init() returns
π Stack:
ββββββββββββββββββββββ
β π§© main() β
ββββββββββββββββββββββ
π¨οΈ Output:
"Hello Init Function!"
β
Program ends gracefully
π CLI Visualization: Execution & Memory Layout (example 2)
=========== Program Compilation ===========
Found global variable: a = 10
Found init() β
Found main() β
=========== Execution Begins ==============
π§ Data Segment (Globals):
a = 10 β initialized before anything runs
π Stack Frame:
ββββββββββββββ
β init() β
ββββββββββββββ
π init() runs
β Prints: 10
β Updates a = 20
Stack after init():
(returns to runtime)
π Stack Frame:
ββββββββββββββ
β main() β
ββββββββββββββ
π main() runs
β Prints: 20
=========== Execution Ends ================
π Summary
β
Global variable a is initialized before any function runs.
βοΈ init() executes first:
Reads a = 10
Changes a = 20
𧨠main() sees updated value: 20
This is a classic example of how init() can prepare or modify the runtime environment before the actual program logic in main() kicks in.
β‘ Quick Recap
-
β
init()
always runs beforemain()
even if itβs written aftermain()
in your code. -
βοΈ You can use it to initialize configs, connections, default values, etc.
-
π‘ A Go file can have at most one
main()
, but multipleinit()
s.
π§ͺ "Init is like the secret backstage crew. You donβt see them during the show, but theyβre the reason the lights come on."