The first Golang program

Let us write a simple Golang program to understand the code structure. The Go code file must have the .go extension. There is no rule for filename, you can give any name to the Go file.

Let us create a hello_world.go file and put the following code:

// Program 1
package main

import "fmt"

func main() {
   fmt.Println("Hello World!!!")
}

Every Go program must have the package declaration. The package declaration statement must be the first statement of the Go program file. In the above program, we have defined the main function. Like other languages, the main is the starting point of the program. It must be declared in the main package. There can be any number of package imports in the Go program. The import statement is optional. When you want to use the functionality of another package, you can import and use it. We have used the Println function of the fmt package. So we imported the fmt package before using it in the code. Like Java, the import statement must be after package declaration.

Compile and run the program

The go tool can be used to compile and run a Go program. We will discuss two commands of the go tool here i.e. go build and go run.

The go build command compiles the Go program and creates the binary. Let us compile Program 1 using the go build command. You need to open the command prompt/ terminal then execute the Change Directory (cd) command to the directory where you have written our first program and run the following command:

go build

If there is no compilation error in the code, this command will create a binary file. The name of the binary file will be the same as the directory name in which you have created the Go program file. For example, you have created hello_world.go program file in the practice directory. The go build command will create a binary file name as practice.

You can execute the binary file like any binary file.

./practice

It will print output on the console as below:

Hello World!!!

Sometimes, you don’t want to generate a binary file as a directory name. you might want to generate the binary file with a different name. For example, you want to generate a binary file as hello. You can achieve this by providing the -o option to the go build command.

go build -o hello

The Golang is a platform-dependent language. It means if you create a binary file in one platform and try to run it on another platform, it will not work. Let us say you have Mac OS and you want to generate a binary file that should be executed on Linus OS with AMD64 architecture. To make it work, you can specify the operating system and architecture while creating the binary file as below.

GOOS=linux GORARC=amd64 go build

A Golang program file can be compiled and executed without generating a binary file. The go run <filename> command compiles and executes the Golang file.

go run hello_world.go

The above command will print the following output on the console:

Hello World!!!