Golang GOPATH and GOROOT

Learn via video courses
Topics Covered

Overview

To build and process the Go source code, a set of instructions is to be executed. GOPATH and GOROOT in Golang are environment variables used for defining the arrangement of source code and the path can be changed if needed. It is the most important path in golang. In this article, we will be covering all about GOPATH and GOROOT in Golang.

Introduction

GOPATH and GOROOT in Golang are environment variables used for defining the arrangement of source code and creating a workspace.

GOPATH in Go Programming

It is also called a directory used for workspace. The Go lang code is stored in the directory. The go-build package is used for the implementation of code/program and to resolve the import statements in case of any error. The first package in the directory in GOPATH is to get tool downloads. If the environmental variable GOPATH is not set then it points to the default directory which is “go” in the home directory of a user. To check it, use the following command as per the operating system:

GOPATH Path Is Defined As

There are 3 directories under the GOPATH and each directory performs specific functions.

  • src: the source code resides in this directory. The path after this directory includes either the import path or the executable name.
  • pkg: the installed package objects reside in this directory. Different operating systems and architecture pair have their subdirectory of pkg.
  • bin: the compiled commands reside in this directory. Every command in Golang is named for its src directory.

GOROOT in GoLang

It is a combination of a compiler and a tool that comes in Golang when it is installed. It is used for finding standard libraries and its path should always be set to the installation directory. For checking the current GOROOT, the following command is used:

The Go tool however can be installed in a different location by setting the environment variable of GOROOT to point to a directory where it was installed originally.

Modifying GOPATH and GOROOT

The GOPATH can be configured to work in a different directory instead of the original directory. However, the same configuration cannot be done for the GOROOT as it comes with some preset tooling that can’t be changed and is hence not recommended.

Conclusion

  • GOPATH and GOROOT in Golang are environment variables used for defining the arrangement of source code and the path can be changed if needed.
  • GOPATH is also called a directory used for workspace.
  • GOROOT is a combination of a compiler and a tool that comes in Golang when it is installed. It is used for finding standard libraries and its path should always be set to the installation directory.
  • The GOPATH can be configured to work in a different directory but cannot be done for the GOROOT as it comes with some preset tooling that can’t be changed.