Open In App

Golang – GOPATH and GOROOT

Improve
Improve
Like Article
Like
Save
Share
Report

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. In order to check the current GOROOT enter the following command:

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

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. 


Last Updated : 30 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads