Entry Points

Like most compiled and statically typed lamguages such as C, C++, Assembler, Fortran etc Golang has a main entry point and a sub entry point that is optional. What do I mean when I say sub entry point and main entry point. The main entry point of a golang program is defined as main while a sub entry point is called init. These are both possible entry points that can be placed wherever in the file.

The init sub entry point###

Golang has a weird file layout which we will go over in a second, but for now lets go over the entry points. The first entry point we are going over is the optional entry point. This function is defined like so.

func init() {
    // Golang code here
}

The init function and entry point can be defined in multiple places throughout the entire source code file or project solution. In this case, an initation function or sub entry point is a function that is typically used for initation of a program. This means that whatever is under the init function will run before main. So, we can build a program to do a small mathematical operation and print it to the screen.

func init() {
  println(2 + 20) // Output: 22
}

and this will then be run before main. This entry point is not a primary entry point for go and can not be used as a final entry point to the program, so we need to use main

The main entry point

This is the actual program entry point within the program, this MUST be declared for a go program to run. To declare a main function we can do it as shown below.

func main() {
    // main code and calls here
}

and when we run our program it will execute.

Clashing with init and main | Rules

INIT functions CAN NOT BE CALLED. This is because the go compiler will prioritize these calls on the backend already and double calling an initation function is not directly supported or should be done anyway.

Below is a list of rules for init and main functions

init or main functions can NOT be called by the user In order to use a init function main must be declared init functions can be declared in any source code file main functions have to be placed in a .go source code file with the package of main

Last updated