What is GOPATH?

In Golang, you need $GOPATH, and a few folders and files. Then type code in the file main.go. You can show the GOPATH using the command

go env GOPATH 

If you get the error below, then Go is not installed correctly on your computer.

Command 'go' not found, but can be installed with:

It shows a folder under your user directory. So GOPATH is a folder under your user folder.

Why GOPATH?

Inside it are 3 directories: bin, pkg, src. In the src directory you can find code you have written.

You don't need to set the GOPATH, it is set by default.

The GOPATH directory is also named a workspace.

Instead of randomly placing your code somewhere, you can use the gopath src directory. This is a mistake many beginners make, placing their code anywhere on the computer.

The reason why you need to know your Go path, is because you store all your projects under its src directory.

Go program directory

In Go, every executable program needs its own directory in the src directory. For instance:

$GOPATH
 /src
  /hello
   /main.go

If you have a github account, you can use a structure like this

/src
  /github.com
   /yourname
    /hello
     /main.go

This is a convention in the Go community.

You can enter your source directory using the command

cd ~/go/src

$GOPATH is not $GOROOT

The directory $GOROOT is another one, it contains the compiler and tools. This is not where you should store your Go source code.

GOPATH *  * isoftenthedirectory * *HOME/go where $HOME is your user folder. For further study on gopath, see the docs

Go workspace

Go workspace contain the directories bin,src and pkg. They have a meaning to the Go tool chain.

- bin
- pkg
- src
  - github.com/blabla
    - example.go

bin When you type go install, the binaries go into $GOPATH/bin. If your program is named example, the program would be:

$ $GOPATH/bin/example

pkg The directory pkg contains compilation files. Usually you dont have to access this directory, GO will take care of it. If you run into compilation errors, you can delete files in this directory.

src This is where all your .go programs are. Your projects code and other projects.