Golang: Getting to grips with Hello World

Okay okay I know, hello world is the most boring application it’s possible to make in any programming language BUT there is a reason that it’s always used, it is quite a good usecase.

In the below, we have the Golang implementation of Hello World and actually, we can derive quite a lot of information about the Golang language from this simple example.

All of our programs in Golang will follow a similar structure:

  • Package declaration
  • Import other packages we need 
  • Declare functions

So, let’s start from line one ‘package main‘. This is the point at which we tell Golang if we’re making an executable or reusable package type.

An executable package is simply that, a piece of code that is executable. A reusable package is like a PHP include or similar, where we have a chunk of code in another Golang file, which we might reference many times throughout different coding projects, hence, it’s reusable but does not execute on its own as a standalone package.

It’s important to note that many files can belong to the same package. As long as every file has ‘package main’ at the top all of them will belong to the main project and will compile together.

Main is a special name. It tells Golang that it’s going to be an executable. Inside of any executable, there must also be a function called main as we have in our above code.

Next, we have import “fmt” which is importing one of the standard Golang libraries. Just like how in Python we might write import pandas as pd, in Golang we also import packages. The fmt package is short for format & is used to print information to the terminal.

Now for the meat of the script func main() { this is short for function and is the same thing as def functionname(): in Python. It enables us to pass arguments in the parenthesis and the body of the function lives within the curly braces.

Next, we have fmt.Println(“Hello World”). This is something I particularly struggled with, as coming from a Python background, I wanted to use single quotes and would get syntax errors. So, it’s really important that you use double quotes for strings in Golang.

Alright, so how do I run it?

If you want to follow along, you can paste this piece of code into a file called filename.go, replace filename with whatever you want.

You can then from the terminal execute run filename.go and the output of Hello World will be printed to the terminal.

Now, the run function simply runs your function. You could use build filename.go, which would compile your application as an executable file. In Linux or Mac, you can run that with simply ./filename and on Windows, you can run the .exe.

There we have it, the end of our first Golang tutorial, I hope it was useful, keep your eyes peeled for more in the coming days.