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

Directory for Go code

To check the current GOPATH enter the following command:

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

To find current GOPATH



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

  • src: It holds source code. The path below this directory determines the import path or the executable name.
  • pkg: It holds installed package objects. Each target operating system and architecture pair has its own subdirectory of pkg.
  • bin: It holds compiled commands. Every command is named for its source directory.

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. 

To check the current GOROOT enter the following command:

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

To find 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. 

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.