Your First Go Program

2-minute read
Table of Contents

We must do the obligatory “Hello World” program. Copy and paste, or preferably type from scratch, the following the program in your favourite text editor:

package main

import "fmt"

func main() {
	fmt.Printf("Hello world!!\n")
}
hello-world.go
Copy

The fmt package contains the Printf() function. This function accepts a set of characters and pushes them into the console.

Running our program

Save the file as “hello-world.go” and run it by using the following command:


go run hello-world.go

The following output will be seen:


Hello world!!

Building a binary out of our program

Go can generate binaries (executables) for your code. This comes in handy when we want to place and run our program in other directories or even other devices (such as a web server) without having to move the source code (hello-world.go in this case) around.

Build the code into a binary by using the following command:


go build hello-world.go
./hello-world

Notice how the binary is usually named after the code file, save the .go extension. These binaries can be generated for multiple platforms so that you can have programs that run everywhere! Each binaries can be its own self-contained app.

Languages such as Python require an interpreter - a program that runs the code line by line - to be present on the device/machine housing the final application. Interpreted programs are generally slower than compiled ones such as those built with Go.

Compiled programs do not need an interpreter. They can run by themselves! Of course, the program must be compiled for that particular device/machine.

Support us via BuyMeACoffee