Managing multiple versions of Go on a single computer can be quite helpful, especially when working on legacy projects that require different Go versions than what you are currently using. This guide will walk you through the steps needed to set up and manage multiple Go versions effectively.

Prerequisites

Before we begin, ensure you have the following tools installed on your system:

  • A shell environment (e.g., bash, zsh)
  • Go programming language installed
  • goenv (a version management tool for Go)

Installing goenv

goenv is a version manager for Go, allowing you to easily switch between multiple versions. Follow these steps to install goenv:

# Install goenv via git

$ git clone https://github.com/syndbg/goenv.git ~/.goenv


# Add the following lines to your ~/.bashrc or ~/.zshrc
export GOENV_ROOT="$HOME/.goenv"
export PATH="$GOENV_ROOT/bin:$PATH"
eval "$(goenv init -)"


# Apply changes

$ source ~/.bashrc # or source ~/.zshrc

You can verify the installation by running:

$ goenv --version

Installing Multiple Go Versions

With goenv set up, you can now install different versions of Go. For instance, to install Go 1.17.3 and Go 1.18, you would execute:

# List all available Go versions

$ goenv install -l


# Install specific Go versions

$ goenv install 1.17.3

$ goenv install 1.18

After installation, these versions will be available for use.

Setting Global and Local Go Versions

Once you have multiple Go versions installed, you can set a global default version which will be used across all your projects unless specified otherwise. To set a global version:

$ goenv global 1.18

For project-specific requirements, you can set a local Go version. Simply navigate to your project directory and run:

$ goenv local 1.17.3

This will create a .go-version file in the project directory, specifying which Go version should be used for that project.

Verifying the Go Version

To ensure you are using the correct Go version, you can verify the installed version with:

$ go version

$ goenv versions

The output will show you currently active Go version and all installed versions. This is useful in ensuring proper setup.

Uninstalling a Go Version

If you wish to remove an old Go version that is no longer needed, use:

$ goenv uninstall 1.17.3

This will free up space and make room for newer versions as necessary.

Conclusion

Managing multiple Go versions is straightforward with goenv. This tool makes switching between projects with different requirements seamless and allows you to keep up-to-date with Go's developments without disrupting existing projects.