Learning Go

So I decided to learn Go in 2017. This will be an ongoing notes as I learn more about it.

Setup Environment

Iā€™m using the excellent guide from How I start. The gist of this setup is to have all my Go code in:-

export GOPATH=~/go/work
export GOROOT=~/go/go

Using binary tarball with custom installation.

This setup allow me to quickly test any Go code by just creating new directory in my $GOPATH/src/github.com/k4ml/reponame and run go build. Having an environment where you can quickly test code is crucial in early stage of learning any new language.

Editor (Vim)

Use fatih/vim-go

mkdir ~/.vim/bundle
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go

Our ~/.vimrc should look like this:-

filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
Plugin 'fatih/vim-go'

" All of your Plugins must be added before the following line
call vundle#end()

filetype plugin indent on " required
syntax on
set shiftwidth=4
set softtabstop=4
set expandtab
set smartindent
set showmatch
set wildmenu
set background=dark
"set relativenumber

set autochdir

if has("autocmd")
    au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif

autocmd Filetype go setlocal ts=4 sw=4 noexpandtab

Re-indent - my default vim setting is to expand tab so copy pasting existing Go code result in 8 spaces indentation.


vim-go will automatically run go-fmt upon saving, so if let say you have wrong syntax, it will show the error:-

Written on January 20, 2017