Go

    When installed, try to run to see the installed version of Go.

    Setup your workspace

    Go has a unique approach of managing code where you have a single workspace for all your Go projects. For more information see the .

    First, you’ll need to tell Go the location of your workspace. We’ll do this by adding some environment variables in your shell config file (usually .bash_profile, .bashrc or .zshrc).

    1. export GOPATH=$HOME/go
    2. export GOROOT=/usr/local/opt/go/libexec
    3. export PATH=$PATH:$GOPATH/bin
    4. export PATH=$PATH:$GOROOT/bin

    Create your workspace

    Create the workspace directories tree:

    1. $ mkdir -p $GOPATH $GOPATH/src $GOPATH/pkg $GOPATH/bin

    $GOPATH/src This is where your Go projects are located
    $GOPATH/pkg A folder that contains every package objects
    $GOPATH/bin The compiled binaries home

    1. package main
    2. import "fmt"
    3. fmt.Printf("hello, world\n")
    4. }

    Run the program by running:

    If you wish to compile it and move it to $GOPATH/bin, then run:

    1. $ go install hello.go

    Since we have $GOPATH/bin added to our $PATH, you can run your program from anywhere:

    Import a Go package

    Besides creating your own packages you can import and use other packages in your Go code. To do so you’ll use the go get command:

    1. $ go get -u github.com/gorilla/mux

    The command above will import the package mux into this directory $GOPATH/src/github.com/gorilla/mux.

    Go has a built-in tool that automatically formats Go source code.

    To format a single file run:

    1. $ gofmt -w yourcode.go

    You can also format an entire package (Note that the command is different from formatting a single file):

    1. $ go fmt path/to/your/package

    Generate documentation

    With the godoc command you can generate documentation from your code and read documentation from other packages.

    1. $ godoc fmt # documentation for package fmt
    2. $ godoc -src fmt # fmt package interface in Go source form

    You need to respect some spec in order to document using godoc. More information in the Godoc documentation.