Open In App

Golang – GOPATH and GOROOT

There is a set of programs to build and process Go source code. Instead of being run directly, programs in that set are usually invoked by the go program. GOPATH and GOROOT are environment variables that define a certain arrangement and organization for the Go source code. The paths of gopath and goroot can be modified explicitly if required. 

GOPATH

GOPATH, also called the workspace directory, is the directory where the Go code belongs. It is implemented by and documented in the go/build package and is used to resolve import statements. The go get tool downloads packages to the first directory in GOPATH. If the environment variable is unset, GOPATH defaults to a subdirectory named “go” in the user’s home directory. To check this, enter the following command:



On Windows: C:\Users\%USERPROFILE%\go
On Linux: $HOME/go

To check the current GOPATH enter the following command:



C:\Users\%USERPROFILE%\go env GOPATH

GOPATH contains 3 directories under it and each directory under it has specific functions:

When using modules in Go, the GOPATH is no longer used to determine imports. However, it is still used to store downloaded source code in pkg and compiled commands bin.

GOROOT

GOROOT is for compiler and tools that come from go installation and is used to find the standard libraries. It should always be set to the installation directory. In order to check the current GOROOT enter the following command:

C:\Users\%USERPROFILE%\go env GOROOT

It is possible to install the Go tools to a different location. This can be done by setting the GOROOT environment variable to point to the directory in which it was installed, although this is not recommended as it comes preset with the tooling. 

Article Tags :