How to Manage Go Versions with goenv

Cli
Use `goenv` to install multiple Go versions and switch between them seamlessly by setting the desired version in your shell configuration or via the `goenv local` command for project-specific isolation.

Use goenv to install multiple Go versions and switch between them seamlessly by setting the desired version in your shell configuration or via the goenv local command for project-specific isolation. This tool manages the GOROOT and PATH variables automatically, ensuring your shell always uses the correct compiler without manual environment tweaking.

First, install goenv (typically via Homebrew on macOS or from source on Linux) and initialize it in your shell profile (~/.zshrc or ~/.bashrc):

# macOS
brew install goenv

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

Once initialized, install a specific Go version (e.g., 1.22.0) and set it as your global default:

goenv install 1.22.0
goenv global 1.22.0

To use a different version for a specific project without affecting your global setup, navigate to the project directory and set a local version. This creates a .go-version file in the directory that goenv reads automatically when you enter the folder:

cd /path/to/my-project
goenv install 1.21.5
goenv local 1.21.5

Now, running go version inside this directory will show 1.21.5, while running it elsewhere will show your global version (1.22.0). You can verify the active version at any time with goenv version.

If you need to list all installed versions or check which versions are available for installation, use:

goenv versions        # List installed versions
goenv install --list  # List available versions

This approach is essential for maintaining compatibility across different projects that may require specific Go releases, or for testing code against the latest stable version while keeping production builds on a pinned, stable release. Remember that goenv only manages the Go binary; it does not replace go mod or handle dependency resolution, so ensure your go.mod file is correctly configured for the active version.