Understanding a go program

Understanding go program

Go programming is all about packages. Every program in golang must belongs to a package.

structure of a go program

  • In first line we have to declare the package
  • After package declaration, write import statements.
  • Now, define variables and functions
  • It's time to define the main function which is the first function to run after the init function when we run the golang program.

Note: Whenever we run a go program it looks for the main package if it finds it then it look for the main function to run the program otherwise it throws an error.

Simple Go program - hello world

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

Above code a simple program to print the "hello world". If you see the code structure we have declared a main package after that we have import statement followed by main function. fmt is a built-in package in go programming which allows us to formate the data and print the output to stdout. Println is one of the functions in the package fmt.

Go program execution example

Let's write a simple golang program to understand the execution flow.

sample.go

package main
import "fmt"

var _ int64 = s()

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

func s() int64 {
    fmt.Println("calling s() func")
    return 1
}

func main() {
    fmt.Println("main func")
}

If we run the above program with command go run sample.go we can get the output like below.

calling s() func
init func
main func
From the above output we can understand that init function always called before execution of the main function.

When to use init function in golang?

  • init() function mostly used to initialize the data for the package before running it.
  • init() is always called, regardless if there's main or not, so if you import a package that has an init function, it will be executed.
  • We can write go programs without init() function also.