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
).
export GOPATH=$HOME/go
export GOROOT=/usr/local/opt/go/libexec
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:$GOROOT/bin
Create your workspace
Create the workspace directories tree:
$ 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
package main
import "fmt"
fmt.Printf("hello, world\n")
}
Run the program by running:
If you wish to compile it and move it to $GOPATH/bin
, then run:
$ 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:
$ 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:
$ gofmt -w yourcode.go
You can also format an entire package (Note that the command is different from formatting a single file):
$ 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.
$ godoc fmt # documentation for package fmt
$ 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 .