What is GOPATH and GOROOT in GoLang
- May 04, 2020
- Adnan Sattar
Go tools expect a certain layout of the source code. GOROOT and GOPATH are environment variables that define this layout. These two are the 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
GOPATH is a variable that defines the root of your workspace. By default, the workspace directory is a directory that is named go within your user home directory (~/go for Linux and macOS, %USERPROFILE%/go for Windows).
GOPATH stores your codebase and all the files that are necessary for your development. You can use another directory as your workspace by configuring GOPATH for different scopes. GOPATH is the root of your workspace and contains the following folders:
src/: location of Go source code (for example, .go, .c, .g, .s).
pkg/: location of compiled package code (for example, .a).
bin/: location of compiled executable programs built by Go.
The GOPATH is the home path where the Go code resides.
This path is defined as follows:
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 a variable that defines where your Go SDK is located. You do not need to change this variable unless you plan to use different Go versions.
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.