EvIsX

荧 · 维思

Homebrew 安装 Golang 开发环境

“安装/配置 开发环境” 需要做什么?

  1. 安装编译器和相关工具
  2. 设置环境变量
  3. 编写 “Hello, World!” 程序进行验证

Homebrew 安装 Go 编译器

  1. Go 编译器(go 命令)
  2. Go 标准库
  3. 其他工具
brew install go
brew list go
# /opt/homebrew/Cellar/go/1.22.1/bin/go
# /opt/homebrew/Cellar/go/1.22.1/bin/gofmt
# /opt/homebrew/Cellar/go/1.22.1/libexec/api/ (25 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/bin/ (2 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/doc/ (5 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/lib/ (4 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/misc/ (26 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/pkg/ (23 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/src/ (9471 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/test/ (3281 files)
# /opt/homebrew/Cellar/go/1.22.1/libexec/ (6 files)
which go
# /opt/homebrew/bin/go

环境变量

go env # 查看所有 go 环境变量(但不是 shell 变量)
# GO111MODULE=''
# GOARCH='arm64'
# GOBIN=''
# GOCACHE='/Users/yyds/Library/Caches/go-build'
# GOENV='/Users/yyds/Library/Application Support/go/env'
# GOEXE=''
# GOEXPERIMENT=''
# GOFLAGS=''
# GOHOSTARCH='arm64'
# GOHOSTOS='darwin'
# GOINSECURE=''
# GOMODCACHE='/Users/yyds/go/pkg/mod'
# GONOPROXY=''
# GONOSUMDB=''
# GOOS='darwin'
# GOPATH='/Users/yyds/go'
# GOPRIVATE=''
# GOPROXY='https://proxy.golang.org,direct'
# GOROOT='/opt/homebrew/Cellar/go/1.22.1/libexec'
# GOSUMDB='sum.golang.org'
# GOTMPDIR=''
# GOTOOLCHAIN='auto'
# GOTOOLDIR='/opt/homebrew/Cellar/go/1.22.1/libexec/pkg/tool/darwin_arm64'
# GOVCS=''
# GOVERSION='go1.22.1'
# GCCGO='gccgo'
# AR='ar'
# CC='cc'
# CXX='c++'
# CGO_ENABLED='1'
# GOMOD='/dev/null'
# GOWORK=''
# CGO_CFLAGS='-O2 -g'
# CGO_CPPFLAGS=''
# CGO_CXXFLAGS='-O2 -g'
# CGO_FFLAGS='-O2 -g'
# CGO_LDFLAGS='-O2 -g'
# PKG_CONFIG='pkg-config'
# GOGCCFLAGS='-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/4l/lr4mjfq53771d9k1_mbmlr7m0000gn/T/go-build632881964=/tmp/go-build -gno-record-gcc-switches -fno-common'
go env GOPATH # 查看某个变量
# /Users/yyds/go
go help environment # 查看 go 环境变量文档
  1. $GOPATH 是 Go 默认的工作区其中有三个主要子目录:
    • $GOPATH/src(存放 Go 源文件的目录)
    • $GOPATH/pkg(存放软件包对象的目录)
    • $GOPATH/bin(存放可执行文件的目录)
  2. 通过 go install 命令安装的工具其可执行文件将存放到 $GOPATH/bin
# 让 $GOPATH/bin 下的命令全局可执行
# 将下面代码写入 shell profile 比如 (zsh: ~/.zshrc)
export GOPATH=$HOME/go          # 以实际 go env GOPATH 为准
export PATH=$GOPATH/bin:$PATH

验证开发环境

// ~/tmp/hello_go/main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
cd ~/hello_go
go run main.go
# Hello, World!