Photo by Eliobed Suarez on Unsplash

How to Get Started Programming in Go

Ricardo Gerardi
The Pragmatic Programmers
6 min readNov 10, 2022

--

Go is an open source programming language that combines a dynamic language’s ease of use with the reliability and performance of a statically typed, compiled language.

https://pragprog.com/newsletter/
https://pragprog.com/newsletter/
In this article:
- Benefits of the Go Programming Language
- Install Go
- Initialize a Go Project
- Use Packages and Imports in Go
- Use the main Function
- Run a Go Application
- Compile a Go Application
- What's Next?

If you’re a sysadmin, you probably write a lot of scripts to perform everyday tasks or automate some of your administration work. You probably accomplish this through a shell script using a scripting language such as Bash, or a programming language like Python or Perl.

Python and Perl are interpreted languages, which have limitations. Some of these limitations include:

  • A particular version of an interpreter must be available both when writing and executing code.
  • Dependencies must be available, both at write time and execution time.
  • Many errors are seen only at runtime, causing your program to stop or break.
  • There can be resource utilization and performance issues for some workloads.

A few years ago, I was working on a project, and I couldn’t use Perl due to these limitations. I needed a new language. That’s when I found Go.

Benefits of the Go Programming Language

Go is an open source programming language combining the ease of use provided by dynamic languages with the reliability and performance provided by statically typed, compiled languages. Even though Go is statically typed (meaning variable types are predefined and known at compile time), the Go compiler can infer those for you, so it often feels like you’re programming in a dynamic language like Python. This makes Go relatively easy to get started with, but it provides the reliability of type validation, which prevents many common runtime errors seen in dynamic languages.

Compiled Go programs provide resource utilization and performance similar to those written in C, but you don’t have to deal with low-level issues like memory management. In addition, Go programs compile to static binaries requiring no dependencies or interpreters at runtime. You can compile your program in your development machine, copy the resulting file to the execution machines, and run it.

Go provides other features, including:

  • A mature and comprehensive standard library and third-party packages
  • Cross-compilation that lets you write and compile programs for different platforms from a single environment
  • Built-in concurrency, so you can use the resources available on your system
  • A complete set of tools, including testing, linting, code validation, and completion

Go is the language of choice for many modern tools, including container management tools such as Podman, Kubernetes, and OpenShift.

Due to these features and benefits, Go fills a gap for people who don’t program all the time but require a powerful and flexible programming language. Go is a great choice of language for network engineers and sysadmins.

Install Go

On Linux, use your distribution’s package manager to install Go (often named golang):

$ sudo dnf install golang

Alternatively, you can download and install it from the official Go download webpage. At the time I’m writing this article, the latest version of Go is 1.19.1. To download this specific version, use curl:

$ curl -sLO https://go.dev/dl/go1.19.1.linux-amd64.tar.gz \ 
--output-dir /tmp/

Then unarchive this file under /usr/local. If you've installed Go previously this way, delete the existing installation first:

$ sudo rm -rf /usr/local/go
$ sudo tar -xzvf /tmp/go1.19.1.linux-amd64.tar.gz -C /usr/local/

Finally, add /usr/local/go/bin to your PATH by adding the following line to your shell's profile. For example, for Bash, add it to ~/.bash_profile:

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

Reload your terminal profile, open another terminal, or log out and back in to make this setting effective. When the variable is set, test Go by running the go version command:

$ go version
go version go1.19.1 linux/amd64

Now you’re ready to start developing your programs in Go.

Initialize a Go Project

To start writing your first Go program, create a folder for your project, and change directory into it:

$ mkdir greet 
$ cd greet

Go uses modules to manage a project’s dependencies. Generally, a module name has to be unique, so by convention, many developers use the name of their source code repository as the module name. For this example, use the module name example/greet.

Initialize your new module:

$ go mod init example/greet
go: creating new go.mod: module example/greet

Use Packages and Imports in Go

Go organizes projects into packages, where each package is a set of related functionalities. To create an executable program, define a package named main with a function called main(). This defines the starting point of your program.

Here’s the start of a common Go program:

package main

import (
"fmt"
"os"
"os/user"
)

The import keyword imports functionality from other packages. In this example, you import three packages from the standard library:

  • fmt provides input and output functions, including functions to print values onscreen.
  • os provides an interface to your operating system, providing appropriate exit codes.
  • os/user allows you to manage system users.

Use the main Function

This sample Go program gets the current user by calling the function user.Current() from the os/user package and stores the result in a variable called u. Then it verifies whether the function call returns an error. If so, it prints an error message and terminates the program. If there's no error, then it prints a greeting message to the current user (by name, thanks to u.Username).

Here’s the code:

func main() {
u, err := user.Current()
if err != nil {
fmt.Println("Cannot get current user:", err)
os.Exit(1)
}

fmt.Printf("Hello %s, welcome!\n", u.Username)
}

Run a Go Application

Save the file and run the program dynamically by using the Go tool go run:

$ go run .
Hello ricardo, welcome!

Compile a Go Application

You can also compile a Go module into a single executable binary with go build:

$ go build

Then run your greet program by calling it directly:

$ ./greet
Hello ricardo, welcome!

What’s Next?

You’ve written, compiled, and executed your first Go program! There is much more you can do. Go is a programming language with clear benefits and features targeted for network engineers and sysadmins. It’s a great choice for developing command-line tools and automation solutions.

I’ve been using Go for many years now, developing several command-line applications, such as log file processing, API clients and servers, network management tools, monitoring tools, data collection, and more. I think Go fits sysadmin work so well that I wrote a book about developing command-line applications with Go. If you’re interested in learning more about Go, take a look at Powerful Command-Line Applications in Go.

In the next article in this series, I’ll explore some additional concepts from the Go programming language.

If you enjoyed this article, you might also enjoy Ricardo’s book, published by The Pragmatic Bookshelf.

Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.

Book cover featuring shadow hands with tools on a streaked blue background
This article was originally published at https://www.redhat.com on November 10, 2022.

--

--

Ricardo Gerardi
The Pragmatic Programmers

Geek, father, consultant, writer. Author of Powerful Command-Line Applications in Go. I also write for many online technical publications. Go, Linux, k8s, Vim.