Whether you installed Golang from Ubuntu official repositories or the Golang backports PPA and you simultaneously installed multiple versions (eg. golang-1.20, golang-1.21, ...), it can be a bit difficult to use them since, technically, the golang-${version}-go packages don't install binaries in system paths and don't create symlinks.
There are some small snippets that help you create symlinks for each version installed and allow easy changing the default version with update-alternatives:
If your shell is Zsh:
: "${INSTALL_BASE_DIR:=/usr/lib}"
for d in "${INSTALL_BASE_DIR}"/go-*.*; do
v="${d##*/go-}"
# Go-1.18 --> priority 1018
# Go-1.21 --> priority 1021
priority=0
ver_components=(${(s:.:)v})
for i in "${ver_components[@]}"; do
priority=$((priority*1000 + i))
done
for exe in go gofmt; do
# Create the go${v}, gofmt${v} symlinks
sudo ln -vfs "${INSTALL_BASE_DIR}/go-${v}/bin/${exe}" "/usr/bin/${exe}${v}"
# Install the go and gofmt alternatives groups
sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${INSTALL_BASE_DIR}/go-${v}/bin/${exe}" "${priority}"
done
done
For bash:
: "${INSTALL_BASE_DIR:=/usr/lib}"
for d in "${INSTALL_BASE_DIR}"/go-*.*; do
v="${d##*/go-}"
# Go-1.18 --> priority 1018
# Go-1.21 --> priority 1021
priority=0
while IFS='.' read -ra ver_components; do
for i in "${ver_components[@]}"; do
priority=$((priority*1000 + i))
done
done <<< "$v"
for exe in go gofmt; do
# Create the go${v}, gofmt${v} symlinks
sudo ln -vfs "${INSTALL_BASE_DIR}/go-${v}/bin/${exe}" "/usr/bin/${exe}${v}"
# Install the go and gofmt alternatives groups
sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${INSTALL_BASE_DIR}/go-${v}/bin/${exe}" "${priority}"
done
done
The code above will set the highest Golang version as the default used by update-alternatives, and also create go${version}, gofmt${version} symlinks for each installed version.