The Go Language

Getting Started

First, download go for your machine, or using a package manager. There's installation instructions if you want to do any additional configuration.

You can actually check out the official tour of Go, which you can run locally.

go get golang.org/x/tour

Your First Program

A heads up, oddly enough, the type comes after the variable name article on Go's declaration syntax

Strings

Creating a string representation of an interface:

type Person struct {
	Name string
	Age  int
}

func (p Person) String() string {
    return fmt.Sprintf("The person named %v is %v years old", p.Name, p.Age)
}

Packages

Programs in go are made up of multiple packages, and will run starting from the code defined in the main package.

You can install go code that you've written using the install subcommand.

For convenience, go commands accept paths relative to the working directory, and default to the package in the current working directory if no other path is given. So in our working directory, the following commands are all equivalent:

# Option 1
go install example.com/user/hello

# Option 2
go install .

# Option 3
go install

There's an interesting article about callback functions using defer


Vim Plugin

If you want to edit your Go projects in Vim, there's a very healthy ecosystem to support you.

" Install the libraries needed for `vim-go`
:GoInstallBinaries
" Getting help
:help vim-go

I've included some useful commands below:

" Run the code in the current buffer
:GoRun

" Compile the code
:GoBuild

" Install the coe
:GoInstall

" Test the code
:GoTest

" Test a single function
:GoTestFunc

" See dependencies of the current package
:GoDeps

" See all source files in cwd
:GoFiles

" Rename an identifier
:GoRename

" Format the document according to the go style guide
:GoFmt

" Resolve all needed package imports & remove all unused packages
:GoImports

" Import the package `math` #study #rise&grind
:GoImport math

" Drop the package `math` #jk2cool4school
:GoDrop math

" Pull up documentation for the function `Printf` package `fmt`
:GoDoc fmt Printf