開始學習 Golang 時已經是 1.20 版了,但很快便陸續推出 1.21, 1.22 版,想說之後很可能會更加踏入這個生態系,先安裝個多版本管理工具避免之後麻煩。

Uninstall original go (optional)

先把原本的 go 移除,將來就以 gvm 管理版本為主。

不過後續似乎會造成 gvm 安裝的問題 (go 1.4 之後),不過之後有時間再把 gvm 移除重新嘗試,或者在 VM 上嘗試。

參考 stackoverflow 上的方法:

sudo rm -rf /usr/local/go
sudo rm /etc/paths.d/go

延伸閱讀: Understanding /etc/paths file and /etc/paths.d directory on MAC

Install gvm

安裝上 document 其實還算詳細,MacOS 有一些 requirements 要先安裝:

xcode-select --install
brew update
brew install mercurial

brew install bison

因為我的 Shell 是 zsh,所以:

zsh < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

但是我的 shell 始終會出現 zsh: = not found.,找了一下始終沒有解法,repo 的 issue 也沒有。後來的 workaround 是進到 bash 去下載,會看到下列訊息:

❯ bash
bash-3.2$ bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
Cloning from https://github.com/moovweb/gvm.git to /Users/cdxvy30/.gvm
macOS detected. User shell is: /bin/zsh
No existing Go versions detected
Installed GVM v1.0.22

Please restart your terminal session or to get started right away run
 `source /Users/cdxvy30/.gvm/scripts/gvm`

接著按照指令:

 source /Users/cdxvy30/.gvm/scripts/gvm

執行 gvm 應該就可以看到下列訊息:

Usage: gvm [command]

Description:
  GVM is the Go Version Manager

Commands:
  version    - print the gvm version number
  get        - gets the latest code (for debugging)
  use        - select a go version to use (--default to set permanently)
  diff       - view changes to Go root
  help       - display this usage text
  implode    - completely remove gvm
  install    - install go versions
  uninstall  - uninstall go versions
  cross      - install go cross compilers
  linkthis   - link this directory into GOPATH
  list       - list installed go versions
  listall    - list available versions
  alias      - manage go version aliases
  pkgset     - manage go packages sets
  pkgenv     - edit the environment for a package set
  applymod   - apply the go version in go.mod

Command

# 列出可遠端下載的版本
gvm listall

# 列出目前的版本
gvm list

gvm gos (installed)

=> go1.20.3
   go1.22.0

Install Go

官方文件的說明:

Go 1.5+ removed the C compilers from the toolchain and replaced them with one written in Go. Obviously, this creates a bootstrapping problem if you don’t already have a working Go install. In order to compile Go 1.5+, make sure Go 1.4 is installed first. If Go 1.4 won’t install try a later version (e.g. go1.5), just make sure you have the -B option after the version number.

gvm install go1.20.3 -B

gvm install issue

gvm 在安裝的時候會等待超久,又沒有進度條的設計當時安裝還以為出現什麼問題,結果只是真的需要很久而已。

gvm install go1.20.3
Downloading Go source...
^CERROR: Canceled!

參考這個 issue 發現滿多人都有遇到,記錄一下。

Setting default

# 設定 default
gvm use go1.20.3 --default

Reference

  1. gvm

  2. Golang - 使用 GVM 管理器安裝 Golang 在 Mac 上