Main and init functions in Golang

Go language has reserved two special purpose functions and those functions are main() and init() . Here are the things to know about using main() and init() functions in Golang .

Main and init functions in Golang

main() function

In Go, the main package is a special package used with executable programs and this package contains the main() function . The main() function is a special type of function and is the entry point for executable programs. It does not take any arguments and does not return anything. Go automatically calls the main() function, so there is no need to call the main() function directly and every executable program must contain a main package and a unique main() function.

For example:

// Chương trình Go minh họa
// khái niệm của hàm main() 

// Khai báo gói chính
package main

// Nhập các gói
import (
    "fmt"
    "sort"
    "strings"
    "time"
)

// Hàm chính
func main() {

    // Sắp xếp slice đưa ra
    s := []int{345, 78, 123, 10, 76, 2, 567, 5}
    sort.Ints(s)
    fmt.Println("Sorted slice: ", s)

    // Tìm chỉ mục
    fmt.Println("Index value: ", strings.Index("Quantrimang", "ks"))

    // Tìm thời gian
    fmt.Println("Time: ", time.Now().Unix())

}

Result:

Sorted slice:  [2 5 10 76 78 123 345 567]
Index value:  3
Time:  1257894000

init() function

The init() function is just like the main function, it does not take any arguments and does not return anything. It is present in every package and is called when the package is initialized. It is implicitly declared, so you cannot reference it from anywhere and you are allowed to create multiple init() functions in the same program and they are executed in the order they are created. You are allowed to create init() functions anywhere in the program and they are called in the order of the dictionary file name (Alphabetical order). You are allowed to put statements if there is an init() function, but always remember that the init() function is executed before the main() function call, so it is independent of the main() function. The main purpose of the init() function is to initialize global variables that cannot be initialized in the global context.

For example:

// Chương trình Go minh họa
// khái niệm của hàm init() 

// Khai báo gói chính
package main

// Nhập gói
import "fmt"

// Hàm init() có nhiều nhánh
func init() {
    fmt.Println("Welcome to init() function")
}

func init() {
    fmt.Println("Hello! init() function")
}

// Hàm chính
func main() {
    fmt.Println("Welcome to main() function")
}

Result:

Welcome to init() function
Hello! init() function
Welcome to main() function
Sign up and earn $1000 a day ⋙

Leave a Comment

Function arguments in Golang

Function arguments in Golang

Go supports two main ways to pass arguments: Pass by Value and Pass by Reference. Go uses pass by value by default.

Function returning multiple values ​​in Golang

Function returning multiple values ​​in Golang

In Go language, you are allowed to return multiple values ​​from a function, using the return statement. In other words, in a function, a return statement can return multiple values.

Switch Statement in Go

Switch Statement in Go

Golang like most other programming languages ​​has switch statement. Here is how to use switch statement in Golang.

Cases to know when using selection statements in Golang

Cases to know when using selection statements in Golang

In this article, we will learn how to use default case to avoid deadlock. But first, we will learn what is deadlock case when using select command in Golang?

Anonymous structures and fields in Golang

Anonymous structures and fields in Golang

Anonymous structs in Golang are temporary structures with no names used for one-time purposes, while anonymous fields allow embedding of unnamed fields.

How to use Rune in Golang

How to use Rune in Golang

What is Rune in Golang? How to use Rune in Golang? This article will give you the answer.

How to use operators in Golang

How to use operators in Golang

Operators allow us to perform different types of operations on operands. In Go language, operators can be classified based on their different functions.

Void identifier in Golang

Void identifier in Golang

_(underscore) in Golang is called Blank Identifier. Identifier is a user-defined name of program elements used for identification purposes.

How to create basic program in Golang

How to create basic program in Golang

Hello, World! is the first basic program in any programming language. You can write this first program in Golang by following the steps below.

How to Install Go on Windows

How to Install Go on Windows

Golang can be easily installed on Windows. Here is a step-by-step guide to install Golang on Windows.

Methods with the same name in Golang

Methods with the same name in Golang

Golang allows creating two or more methods with the same name in the same package, but the receivers of these methods must be of different types.

Functions in Go

Functions in Go

In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time.

Variable Scope in Go

Variable Scope in Go

The scope of a variable in Golang determines which part of the program the variable is accessible to. In Go, all identifiers have a lexical scope that is determined at compile time.

Control Statements in Golang (if, if-else, Nested-if)

Control Statements in Golang (if, if-else, Nested-if)

What conditional statements does Golang have? How to use conditional statements in Go programming? Let's find out together!

Short variable declaration operator in Go

Short variable declaration operator in Go

The short variable declaration operator (:=) in Golang is used to create variables with a proper name and initial value. Here is what you need to know about the short variable declaration operator in Golang.

Gemma 2 or Llama 3 is the best open source model?

Gemma 2 or Llama 3 is the best open source model?

The new Gemma 2 27B model is said to be very promising, outperforming some larger models like the Llama 3 70B and Qwen 1.5 32B.

Figma Can Use Your Content to Train AI: How to Prevent It?

Figma Can Use Your Content to Train AI: How to Prevent It?

With Figma's latest AI announcement comes concerns about how the tool might use users' creative work to train AI.

Google confirms issue with second-generation Chromecast and Chromecast Audio

Google confirms issue with second-generation Chromecast and Chromecast Audio

After a few days of confusion, Google has officially confirmed the issue with both the second-generation Chromecast and Chromecast Audio.

Update Firefox now before it becomes a security risk!

Update Firefox now before it becomes a security risk!

Unfortunately, it seems that bad guys have found a vulnerability in Firefox and are actively using it right now.

How to change design colors on Canva is very simple

How to change design colors on Canva is very simple

Canva supports you with many tools to change your design very professionally. For example, you can change the design color on Cava with just a simple click.

How to insert citations in Google Docs

How to insert citations in Google Docs

Reference citations in Google Docs make it easier for readers to refer to the content in the document. And in the process of adding citations, users can change them to suit the document.

How to Recover Locked WhatsApp Account

How to Recover Locked WhatsApp Account

WhatsApp accounts are locked for many reasons, it could be because you did something that caused Meta to lock your WhatsApp account or because of Meta.

How to Erase Any Detail in an Image with GIMP

How to Erase Any Detail in an Image with GIMP

With GIMP, often jokingly referred to as the free version of Photoshop, users can easily remove objects in the background of images with just a few tools. This technique requires a little patience to get the best results.

Latest FC Mobile Code 04/25/2025

Latest FC Mobile Code 04/25/2025

FC Mobile Code contains many rewards such as FC Point, player package, diamond package... Below we have compiled the latest FC Mobile giftcodes along with how to redeem codes to receive rewards.

Full list of latest AFK Journey codes and how to redeem codes

Full list of latest AFK Journey codes and how to redeem codes

AFK Journey Code will help players have a smoother and easier start in their journey.

Latest XSamkok Super Energy Three Kingdoms Code and how to enter code

Latest XSamkok Super Energy Three Kingdoms Code and how to enter code

Code Xsamkok Super Energy Three Kingdoms gives players a series of rewards when exchanging codes.

How to convert money amounts to words in Excel, no add-in needed, supports both 32-bit and 64-bit Excel

How to convert money amounts to words in Excel, no add-in needed, supports both 32-bit and 64-bit Excel

Convert numbers to words in Excel, convert amounts to words with Excel versions from 2003 to 2016, Excel is free like WPS Office, no need to install add-ins, supports both 32-bit and 64-bit versions.

How to calculate percentage (%) in Google Sheets

How to calculate percentage (%) in Google Sheets

What is the percentage function in Google Sheets? How to calculate percentage in Google Sheets? Let's find out with Quantrimang.com!

Download AutoCAD 2020 free license (AutoCAD Student)

Download AutoCAD 2020 free license (AutoCAD Student)

Autodesk AutoCAD 2020 has a free download program for those who are students, students or teachers with copyrighted software. Users only need to use the confirmation document and that's it.

How to perform a search on a Samsung Galaxy phone

How to perform a search on a Samsung Galaxy phone

The idea behind Samsung's system-wide internal search feature is to help users find everything they need on their device from a single area, with simple, quick operations.