Learning Go by examples: part 1 - Introduction

Why Golang?

Former Java developer for 10 years, I discovered Golang (aka Go) over 4 years ago and fell in love with its simplicity and learning curve. It's easy to start creating an application in Go but you have to dig deeper to avoid falling into certain pitfalls ^^.

I like the explanation by example, so in this new series of articles, I will try to introduce you to Go with concrete applications in each article.

Let's start this serie with a prerequisite ;-).

Installation

The first thing to do is to install Golang in your local computer. You can follow the installation procedure on the official website but I recommend to install and use GVM, a Go version manager, that will allow you to install and update the versions of Go by specifying which version you want.

For bash:

bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

For zsh:

zsh < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

Usage:

$ gvm
Usage: gvm [command]

Description:
  GVM is the Go Version Manager

Commands:
  version    - print the gvm version number
  get        - gets the latest code (for debugging)
  use        - select a go version to use (--default to set permanently)
  diff       - view changes to Go root
  help       - display this usage text
  implode    - completely remove gvm
  install    - install go versions
  uninstall  - uninstall go versions
  cross      - install go cross compilers
  linkthis   - link this directory into GOPATH
  list       - list installed go versions
  listall    - list available versions
  alias      - manage go version aliases
  pkgset     - manage go packages sets
  pkgenv     - edit the environment for a package set

The GVM command that will interest us especially is the command gvm install, which we can use like this:

$ gvm install [version] [options]

Go installation:

$ gvm install go1.16.5 -B
$ gvm use go1.16.5 --default

In your .zshrc or .bashrc file, set your $GOROOT and $GOPATH environment variables.

Here is an example:

[[ -s "$HOME/.gvm/scripts/gvm" ]] && source "$HOME/.gvm/scripts/gvm"
export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=${PATH}:$GOBIN:$GOROOT/bin

Now we can check our current Go version:

$ go version
go version go1.16.5 darwin/amd64

Conclusion

Cool!
We now know how to install and switch between different versions of Go. We now can create our first applications!

40