GOPATH and GOROOT: What to Set and Why It Matters
\n\nIf you are just starting to learn Go, sooner or later you will come across the magic abbreviations GOPATH and GOROOT. The question "What should be the values of GOPATH and GOROOT?" is one of the most popular on Stack Overflow, and for good reason. Beginners get confused, set them incorrectly, and get strange errors when building projects.
In this article, we will explain in simple terms what these variables are for, what default values to assign them, and how to switch to the modern approach with go modules. Let's go!
What is GOROOT?
\n\nGOROOT is the path to the folder where the Go compiler itself is installed. Inside this folder are the standard packages (fmt, net, os, etc.), as well as the binaries go, gofmt, and other utilities.
Most developers do not need to explicitly set GOROOT. If you installed Go through the official installer or package manager, the compiler knows where it is.
\n\nHow to check the current GOROOT value?
\nOpen a terminal and run:
\ngo env GOROOT\n\nExample output on Linux:
\n/usr/local/go\n\nOn Windows (if installed to the default location):
\nC:\\Program Files\\Go\n\nWhen should you change GOROOT?
\n- \n
- If you moved the Go folder to another location. \n
- If you have multiple Go versions installed and want to switch between them. \n
- If you compile Go from source and installed it to a non-standard directory. \n
In all other cases, leave GOROOT alone — let Go take care of it.
\n\nWhat is GOPATH?
\n\nNow, GOPATH is a much more interesting variable. Historically, Go required all your code to be in a single workspace. This workspace was defined by GOPATH.
By default, GOPATH points to:
- \n
- Linux/macOS:
$HOME/go\n - Windows:
%USERPROFILE%\\go\n
Inside this folder, the standard structure is:
\ngo/\n├── bin/ # compiled binaries\n├── pkg/ # built object files and cache\n└── src/ # source code of your projects\n ├── github.com/\n │ └── user/\n │ └── myproject/\n └── example.com/\n └── myapp/\n\nHow to check the current GOPATH value?
\ngo env GOPATH\n\nWhat should be in GOPATH and GOROOT? (Correct Values)
\n\nHere is the short answer to the main question:
\n\n| Variable | \nDefault Value (Linux/macOS) | \nDefault Value (Windows) | \n
|---|---|---|
GOROOT | \n /usr/local/go | \n C:\\Program Files\\Go | \n
GOPATH | \n $HOME/go | \n %USERPROFILE%\\go | \n
Important: GOPATH and GOROOT must be different folders. Never set them to the same value!
Common Mistakes and How to Fix Them
\n\nMistake 1: "GOPATH not set" or "cannot find package"
\nIf you are using the old approach (before versions 1.11-1.13), Go looks for packages inside $GOPATH/src. If you placed your project in a different location, the compiler won't find it.
Solution:
\n- \n
- Either move the project to
$GOPATH/src. \n - Or