DEV Community

Cover image for Go 101: Hello, World!
Guillaume Jacobs
Guillaume Jacobs

Posted on

Go 101: Hello, World!

Go, or Golang, is a programming language pioneered by three Google employees: Robert Griesemer, Robert Pike, and Kenneth Thompson. Firstly announced in 2009, version 1.0 of the language was released to the public in early 2012. The two main goals of the creators were to create a language that enforces software engineering’s good practices as well as making the process of working on large systems more productive and scalable.

Go is a fairly easy language to learn, yet is very powerful. This feature has helped Go progressively replacing C in some area while conserving C's best features. Indeed, Go is a statically typed language (which helps create safer and better-designed programs) as well as a compiled language (which improves run-time efficiency).

The team behind Go has been working hard on trying to make it as user friendly as possible in the past years by packaging countless tools with the Go compiler. Furthermore, Go is an open source project, with a huge support from the community and has an enormous amount of tools and libraries available to facilitate the development of Go programs.

Thanks to this, in the past years, Go has been continuously voted one of the most-loved programming languages in different indexes and surveys, including Stack Overflow annual surveys.

Two of the most famous modern software tools out there, Docker and Kubernetes, have been built with Go. Many companies, such as Google, IBM, and Uber, have also migrated part of their production services to Go.

For all of those reasons, Go is really worth learning. It will become more and more relevant over the years to come, especially in the microservices and DevOps area where it has seen an outstanding growth.

Prerequisites and basic concepts

In order to write your first program in Go, you will firstly need to fulfil some prerequisites.

The first one, quite obviously, is to install Go’s toolset. You can do so by navigating to the Go download page and installing the latest stable release of Go for your operating system.

Secondly, and this part is specifically for those of you without any programming experience, you will need to install a code editor as well as setting up your terminal. The code editor is the place where you will write your code. As a personal preference, I really recommend Visual Studio Code, which is fairly easy to use and also offers support for Go via plugins (auto-formatting, autocompletion, and more).

On the other hand, the terminal is the place where you will run commands (in order to build or run your code, navigate through your projects, etc...). Opening your terminal is dependent on which operating system you are using:

  • Windows: The terminal, or command prompt, is accessed by pressing the Windows key + R. You should then type “cmd.exe” and hit Enter.

  • Mac: The terminal can be accessed by opening your Finder, then by clicking on Applications, followed by Utilities. From there, you can start the terminal application.

To verify that the previous steps have been successful, you can write the following command in your terminal

go version

If you have followed along correctly, you should see an output on your terminal telling you which version of Go you are currently using, similarly to the following snippet.

go version go1.18 darwin/amd64

It is possible, for various reasons, that you might get an error while trying to run the previous command. If so, please refer to the comments section of this post and we will try to solve your issue. You can also, as a good practice, google your issue and find a solution on websites like Stack Overflow.

The most common issues are when you download the Go toolset for a different OS architecture than yours, or when the Go binary is not properly located in your executable path. It can be the case if you are using zsh instead of a Bash shell with a Mac (the error being go command not found). In that specific case, you have to add the path to the go executable to your .zshrc file located in your home directory. Add the following line, save, and the go command should now be available.

export PATH=$PATH:/usr/local/go/bin

The last thing that you need in order to build your first Go program is an understanding of the gopath. The gopath is an environment variable that tells Go where to look for source code, compiled packages, or executable binaries on your computer. By default, the gopath is located in your user’s home folder and doesn't need any extra configuration (Users/YourName/go for Mac and Linux, c:\Users\YourName\go for Windows).

This go directory should be subdivided into three sub-directories, namely src, bin and pkg. In order to create those sub-directories (if they weren't created by default or if you chose a different location), you should use your terminal and run the following commands inside your home directory:

  • On Windows:
md go
cd go
md src bin pkg
Enter fullscreen mode Exit fullscreen mode
  • On Mac or Linux
mkdir go
cd go 
mkdir src bin pkg
Enter fullscreen mode Exit fullscreen mode

The src subdirectory is the most important one for the moment, as it is the one where our source code will live. The two other subdirectories will store compiled packages as well as executable binaries.

"Hello, World!"

In order to build our first program, we firstly need to create a new directory inside the src directory, and create an empty go file inside of it. For the sake of our tutorial, let’s call our new directory hello and our file main.go. To do so, let’s run the following commands in our terminal. Depending on your OS:

  • On Windows
md src\hello
cd src\hello
copy nul main.go
Enter fullscreen mode Exit fullscreen mode
  • On Mac or Linux
mkdir src/hello
cd src/hello
touch main.go
Enter fullscreen mode Exit fullscreen mode

Those commands will create the hello directory, allow you to navigate into that same directory, and finally create an empty file named main, with a go file extension (telling Go’s toolset that what is inside this file is code written in Go).

From there, you need to open the newly created file with your text editor of choice. If you are using VS Code, and you have installed the code command using the command palette, you can simply run the following command from your terminal.

code .

This will open the current working directory directly into VS Code. If you haven't made those configuration, you can directly open the hello directory from VS Code.

Once you have opened the main.go file with your code editor, you should write the following code and save it. Beware that the indentation and position of the brackets are very important for the program to compile.

Let’s now go over each line of code and explain what is happening, step by step.

  1. package main: This is known as a package declaration. Each Go program starts with a package declaration. The reason is to encourage better software design and code reusability. In order to run a program in Go, you must define a package named "main". It doesn’t matter what our file is called (we could have called it hello.go). What is important is that the compiler needs to find this package main line to produce an executable file successfully (any other package name would be considered as a library). It is important to note that every file within the same directory should have the same package name.

  2. import "fmt": The import keyword is used to import source code from another package. In this case, we import a package called “fmt” (shorthand for formatting). This built-in package with Go language is used to format inputs and outputs (we will use it mainly to print outputs to the terminal while running our programs). We can, of course, import multiple packages inside the same file.

  3. func main() { }: This is called a function declaration. A function must start with the keyword func. This keyword is followed by the name of the function (in this case, main). Between the parentheses, we can define a series of parameters. For example, we could imagine a function that would sum up two numbers. Our function would then have two parameters, a and b, our two numbers. Between the curly braces is the body of the function. This is where we define what our function actually does. Every main package should have one function called main. This is indeed the entry point to our program. Without this main function, our program wouldn’t compile. It is also important to mention that this main function cannot take any argument nor return any value (as opposed to C).

  4. fmt.Println("Hello, World!"): This is the only line of the body of our function. In this line, we access the Println function defined in the fmt package. To this function, we pass the following argument: “Hello, World!”. This argument is known as a string. A string, in Go, characterises any set of characters defined between double quotes. This Println function is therefore invoked in our main function, which provokes our terminal to output the following line once the program runs.

Hello, World!

Running the Program

As said earlier, Go is a compiled language. Thus, our program firstly needs to be compiled into machine code in order to be run. To do so, there are two options that we can use in our terminal.

Firstly, we can compile our program with the following command:

go build main.go

Once the program is compiled, we can then directly run the newly created binary executable, using the following command:

  • On Windows

main

  • On Mac or Linux

./main

This entire workflow can also be accomplished using a single command:

go run main.go

The latest command actually does two things behind the scene. It firstly runs the go build command, and then executes the freshly created binary. All of this happen within a temporary directory, which is then deleted once the program is done executing.

While the go run command is useful in a development setup or for scripting purposes, the persistent binary file created by go build should be privileged in a production setup, especially for performance reasons.

Goodbye, World!

Congratulations! If you have followed along this tutorial, you should have managed to run your first Go program. If anything went wrong along the way, feel free to reach out to me in the comments and I will help you troubleshoot your issue.

In this tutorial, we have covered the very basics of Go, from setting up your local environment to running your first program. In the next tutorials, we will cover in details the different main features of Go, including its data types, control flow, and functions, amongst many other aspects of the language. I am looking forward to it, and I hope you will enjoy the journey!

Top comments (0)