效果如下:
❯ echo $PATH
/opt/homebrew/opt/openjdk/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin
❯ go version
go version go1.20.5 darwin/arm64
❯ brew unlink go && brew unlink go@1.18 && brew link go@1.18 && go version
Unlinking /opt/homebrew/Cellar/go/1.20.5... 2 symlinks removed.
Unlinking /opt/homebrew/Cellar/go@1.18/1.18.10... 0 symlinks removed.
Linking /opt/homebrew/Cellar/go@1.18/1.18.10... 2 symlinks created.
If you need to have this software first in your PATH instead consider running:
echo 'export PATH="/opt/homebrew/opt/go@1.18/bin:$PATH"' >> ~/.zshrc
go version go1.18.10 darwin/arm64
❯ brew unlink go && brew unlink go@1.18 && brew link go && go version
Unlinking /opt/homebrew/Cellar/go/1.20.5... 0 symlinks removed.
Unlinking /opt/homebrew/Cellar/go@1.18/1.18.10... 2 symlinks removed.
Linking /opt/homebrew/Cellar/go/1.20.5... 2 symlinks created.
go version go1.20.5 darwin/arm64
当我想要切换go版本时发现 大部分搜索到的资料显示使用 brew switch 如这篇 MacOSX系统下HomeBrew安装指定版本的软件 & IntelliJ IDEA 设置多个Go语言版本开发,不过这个命令在我本地是不生效的
❯ brew -v
Homebrew 4.0.26
❯ brew switch go@1.18
Error: Unknown command: switch
于是我又去github找到了这篇讨论 What is the syntax for brew link @-versioned formulae? 2.6.x版本之后就弃用了switch命令,可以通过link命令来切换版本,参考其中一个回答。
Switch from v6 to v7:
brew unlink cf-cli@6 && brew unlink cf-cli@7 && brew link cf-cli@7 && cf version
刚开始我还发现本地执行完上面命令不生效的情况,后来我输出path,看到我之前主动在配置文件中设置过gopath,所以不符合预期,于是又参考这篇 macos设置环境变量path详解,找到曾经在‘~/.zprofile’主动设置的配置删除,source ~/.zprofile 重新加载配置。
还没结束,要注意如果你和我一样,执行完source命令并没有重新开一个终端,你会发现,神马情况,没生效?接着尝试最后一步,新开一个终端在输入命令看看结果是否生效了:)