2 min read

Golang Tutorial 1: Introduction

Golang Tutorial 1: Introduction

In this tutorial, you will learn how to install golang, setup you vscode and write a simple hello world program.

1. Installing go

1.1 Mac

There are multiple ways you can install go in mac. The best and easy way to install and handle versioning of golang is home brew.

brew update
brew install golang

Another way to install go is from the official website. But, disadvantage of this is version control and upgrades of go should be done manually.

1.2 Linux

Installing using snap:

sudo snap install go

Installing using apt-get:

sudo apt-get install golang

Installing using yum:  

sudo yum install golang

1.3 Windows

You can install go using executable from the official website.

2. Setting up go environment

After go is installed, you should create a workspace with bin, pkg and src folders. Once these folders are created, GOPATH should be set to the workspace folder. Additionaly PATH should be set to $GOPATH/bin.

export GOPATH=$HOME/workspace
export PATH=$GOPATH/bin

After go modules were introduced, creating workspace is not mandatory. You need to go mod if you want the project to be outside of GOPATH.

If we need to set these environment variable in shell config for mac, you need to add these to one of the following config files.

1. ~/.bash_profile
2. ~/.bashrc
3. ~/.zshrc (If you are using zsh)

For linux:

1. ~/.bashrc

For windows, goto System (Control panel) -> Advanced system settings -> Advanced tab -> Environment variables button on the bottom right.

3. Setting up vscode

First, you need to install the official go extension for vscode. Ensure, that Use language server is enabled for naviagation and auto complete. You can also set these settings in settings.json. Below is my settings.json for vscode.

{
    "go.lintTool": "revive",
    "workbench.colorTheme": "Monokai",
    "[go]": {
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        },
        "files.eol": "\n"
    },
    "[go.mod]": {
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": true,
        },
    },
    "gopls": {
        "completeUnimported": true,
        "usePlaceholders": true,
        "completionDocumentation": true,
        "hoverKind": "SynopsisDocumentation"
    },
    "go.trace.server": "verbose",
    "go.useLanguageServer": true,
    "go.lintOnSave": "off",
    "editor.largeFileOptimizations": false

}

4. Hello world program

Once vscode is setup, let us write our first program in go. Unless you are using go module, create a folder hello-world in GOPATH/src. Create a new file main.go.

package main

import "fmt"

func main() {
	fmt.Println("Hello world")
}

Conclusion

Thats it, you have successfully setup go+vscode and written you first program in go.