GOPATH and GOROOT in Go Programming

GOPATH and GOROOT are two most essential PATHs in GoLang. The go tool uses it to do the task in a better way. Now, we are going to take a look at what each one represents.

GOPATH in Go Programming

The GOPATH is the home path where the Go code resides.

This path is defined as follows:

$HOME/go          // Unix-based systems
%USERPROFILE%\go  // windows

The GOPATH is used to resolve imports, as well as to install packages outside the go tree.

It is a path variable that is used by the go tool to look for go code written by users.

Here’s an example, suppose a project is done under the src folder under GOPATH, then the go build command will create the executable in the bin directory in the GOPATH.

This is a very efficient way to handle distributions of software, since the directories are predefined we need to focus less on managing different folders in our projects.

Now, what happens when we install a package using go get?

This is where the GOROOT comes in.

GOROOT in GoLang

GOROOT is the place where the go installation took place. And it is recommended not to set it by yourself. Go tooling comes with it already set up.

E.g. in windows GOROOT can be C:\go.

GOROOT is used to locate installation directories for external packages we install.

Modifying GOPATH and GOROOT

In the end, we can configure GOPATH to work in a different directory, but we should not put our hands to GOROOT as it comes preset with the tooling, so it is not recommended.