Skip to content

Latest commit

 

History

History
76 lines (50 loc) · 2.21 KB

setup-environment.md

File metadata and controls

76 lines (50 loc) · 2.21 KB

Setting Up Your Go Environment

For Mac OS X users the simplest way to install Go is to use homebrew:

$ brew install go

Once installed you should probably do the following steps (not entirely necessary, but recommended):

Step 1: Set Your GOPATH

Add the following lines to your .bashrc:

export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

then source your .bashrc or open a new terminal to load it.

Step 2: Create Your GOPATH Directory

Run the following command to create your GOPATH directory:

$ mkdir $HOME/go

Create Your First Program

Start by creating a directory for your program. Let's call the folder hello and align it with your GitHub account:

$ mkdir -p $GOPATH/src/github.com/user
$ mkdir $GOPATH/src/github.com/user/hello
$ cd $GOPATH/src/github.com/user/hello

Next, create a file named main.go inside the hello/ directory, containing the following Go code.

package main

import "fmt"

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

Now you can build and install that program with the go command-line tool (make sure you are inside your hello/ directory):

$ go install

This command builds the hello command, producing an executable binary. It then installs that binary to the workspace's bin directory as hello.

$ $GOPATH/bin/hello
Hello World.

Once you have added $GOPATH/bin to your PATH(e.g. $ export PATH=$PATH:$GOPATH/bin), just type the binary name:

$ hello
Hello World.

A Few Points

The choice of the filename main.go was arbitrary. You could have called it sample.go or first.go. The name of the binary hello is actually derived from the directory name hello. The go command-line tool uses the name of the final directory containing your package main file(s) to name the binary. So for example, if you created a file under the path ~/go/src/a/b/c/d/umbrella/rain.go then the name of the binary generated by go install will be umbrella.

All your Go code must live under $GOPATH/src. This takes a bit of getting used to i.e. not being able to build a Go project at an arbitrary location in your file-system. The good news is most folks like it!