Skip to main content

Setting up Go Path

Before we delve into writing our first Go program, it's essential to understand and set up your GOPATH. GOPATH is an environment variable in Go that specifies the location of your workspace.

What is GOPATH?

In Go, all your source files, compiled binaries, and external packages downloaded from the internet are stored in a specific directory layout. This directory layout is called your workspace. The GOPATH environment variable points to this workspace.

Typically, a workspace contains three directories at its root:

  • src: Contains Go source files organized into packages.
  • pkg: Contains package objects.
  • bin: Contains executable commands.

How to Set Up GOPATH?

Setting up your GOPATH is a fundamental step in running Go programs. Here's how to do it:

For Linux or Mac:

  1. Open your terminal.
  2. Open your .bashrc or .bash_profile file in a text editor. For example, you can use the nano command:
    nano ~/.bashrc
  3. Add the following lines to the file:
    export GOPATH=$HOME/go
    export PATH=$PATH:$GOPATH/bin
  4. Save and close the file.
  5. To apply the changes, use the source command:
    source ~/.bashrc
  6. Verify your setup by typing echo $GOPATH in your terminal. It should output the path you just added.

For Windows:

  1. Open the 'System' window (right-click on 'Computer' on the desktop and choose 'Properties').
  2. Click 'Advanced system settings'.
  3. In the 'System Properties' window that appears, click 'Environment Variables'.
  4. In the 'User variables' section, click 'New' to open the 'New User Variable' dialog.
  5. Enter GOPATH in the 'Variable name' field.
  6. Enter your chosen directory path in the 'Variable value' field.
  7. Click 'OK' in all dialog boxes to apply the changes.
  8. To verify, open a new command prompt and type echo %GOPATH%. It should display the path you just added.

Conclusion

Setting up GOPATH is a crucial step in writing Go programs. It tells Go where to look for its workspace. Once you've set up your GOPATH, you can start building Go programs. Remember, every Go program you write or any external Go package you install will be stored in the workspace pointed to by your GOPATH. Therefore, make sure you select a directory that has sufficient storage space.

Setting up your environment correctly from the beginning will save you from potential issues and confusions in future. So, take your time to correctly setup your Go environment. Happy coding!