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
1 | go env GOPATH |
If you get the error below, then Go is not installed correctly on your computer.
1 | 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.
1 | 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:
1 | $GOPATH |
If you have a github account, you can use a structure like this
1 | /src |
This is a convention in the Go community.
You can enter your source directory using the command
1 | 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 is often the directory $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.
1 | - bin |
bin
When you type go install
, the binaries go into $GOPATH/bin
.
If your program is named example, the program would be:
1 | $ $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.
Leave a Reply