What is init() function in Go language?

Go language | init() function: In this tutorial, we are going to learn about the init() function, what is it, and how to use it?
Submitted by IncludeHelp, on October 02, 2021

In Go programming language, the init() function is just like the main() function. But, the init() function does not take any argument nor return anything. The init() function is present in every package and it is caked when the package is initialized.

The init() function is declared implicitly, so we cannot reference it, we are also allowed to create more than one init() function in the same program and they execute in the order they are created.

Syntax:

func init {
   // initialization code here    
}

Example 1:

// Golang program to demonstrate the
// example of init() function

package main

import (
	"fmt"
)

func init() {
	fmt.Println("[1] init is called...")
}

func init() {
	fmt.Println("[2] init is called...")
}

// Main function
func main() {
	fmt.Println("Hello, world!")
}

func init() {
	fmt.Println("[3] init is called...")
}

Output:

[1] init is called...
[2] init is called...
[3] init is called...
Hello, world!

Example 2:

// Golang program to demonstrate the
// example of init() function

package main

import (
	"fmt"
)

// Global variables
var name string
var age int

func init() {
	// Assign default values to global variables
	name = "Unknonw"
	age = 0

}

func main() {
	// Printing the variables
	fmt.Println("Name:", name)
	fmt.Println("Age :", age)

	// Update the values
	name = "Alex"
	age = 21

	// After updating,
	// printing the variables
	fmt.Println("After updating...")
	fmt.Println("Name:", name)
	fmt.Println("Age :", age)
}

Output:

Name: Unknonw
Age : 0
After updating...
Name: Alex
Age : 21

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.