macOS配置 GO语言环境
在 macOS 上配置 Go 语言环境的两种步骤:
方法一:使用 Homebrew 安装
-
安装 Homebrew(如果还没有安装):
macOS 安装 Homebrew -
使用 Homebrew 安装 Go:
brew install go
方法二:手动安装 (推荐)
- 下载 Go:
- 访问 https://golang.google.cn/dl/
- 下载适合 macOS 的最新版本
- 安装下载的包文件:
- 双击下载的
.pkg
文件 - 按照安装向导完成安装
- 双击下载的
- 安装地址默认为 /usr/local/go
~% /usr/local/go/bin/go version
go version go1.24.5 darwin/amd64
配置环境变量
安装完成后,需要配置环境变量。
# 如果使用 zsh(macOS Catalina 及以后版本的默认 shell)
nano ~/.zshrc# 如果使用 bash
nano ~/.bash_profile
添加以下内容:
# Go 环境变量
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
保存后,重新加载配置:
source ~/.zshrc # 或 source ~/.bash_profile
验证安装
运行以下命令验证 Go 是否安装成功:
go version
设置 Go 模块代理(可选,推荐国内用户设置)
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOSUMDB=sum.golang.google.cn
创建第一个 Go 程序
- 创建工作目录:
mkdir ~/go/src/hello
cd ~/go/src/hello
- 创建 main.go 文件:
cat > main.go << 'EOF'
package mainimport "fmt"func main() {fmt.Println("Hello, Go!")
}
EOF
- 运行程序:
go run main.go