DEV Community

Cover image for How to install Go and write a HelloWorld program in 4 steps
Lukas Lukac
Lukas Lukac

Posted on • Originally published at web3.coach

How to install Go and write a HelloWorld program in 4 steps

There is something about the official Go installation instructions that keep confusing developers, myself included - so here is a quick tutorial on how I setup Go on my new MSI laptop running the latest Ubuntu 20.

1/4 Download Go

Visit Go web and check the latest version: 1.14.2

Fetch the Go source to /usr/local/ dir:

sudo wget -c https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local
Enter fullscreen mode Exit fullscreen mode

2/4 Configure the ENV

I like to keep all my Go projects in $HOME/go.

Depending on your setup, add the following 2 env variables to your shell configs and define the desired paths.

Check your shell:

echo $SHELL
/usr/bin/zsh
Enter fullscreen mode Exit fullscreen mode

Because I use ZSH, I will add the 2 vars to the $HOME/.zshrc config file:

export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
Enter fullscreen mode Exit fullscreen mode

Reload the config:

source $HOME/.zshrc
Enter fullscreen mode Exit fullscreen mode

3/4 Validate the installation

go version
go version go1.14.2 linux/amd64

echo $GOPATH
/home/web3coach/go

echo $PATH
usr/local/go/bin:/home/web3coach/go/bin
Enter fullscreen mode Exit fullscreen mode

Perfect. Let's write a simple Go program to ensure everything works well.

4/4 Program Hello

Create the Hello's project dir:

mkdir -p $HOME/go/src/hello
cd $HOME/go/src/hello
touch hello.go
Enter fullscreen mode Exit fullscreen mode

Paste the following Hello's code into the ./hello.go file:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
Enter fullscreen mode Exit fullscreen mode

Compile

go install
Enter fullscreen mode Exit fullscreen mode

A new program's binary will be generated and stored in $GOPATH/bin dir:

ls -la $GOPATH/bin

drwxrwxr-x 2 web3coach web3coach    4096 čec  5 19:25 .
drwxrwxr-x 4 web3coach web3coach    4096 čec  5 19:25 ..
-rwxrwxr-x 1 web3coach web3coach 2076690 čec  5 19:25 hello
Enter fullscreen mode Exit fullscreen mode

hello is your new generated program's binary. You can now execute it from any directory because the $GOPATH/bin is included in your previously configured $PATH.

hello
Enter fullscreen mode Exit fullscreen mode

Output: "Hello, World!"

Summary

You installed Go 1.14.2 and fully setup its environment. If you want to know how to develop a blockchain from scratch in Go - follow me on Twitter: https://twitter.com/Web3Coach

Top comments (0)