Go 语言环境安装

三平台装 Go、配 GOPATH 与代理、验证安装。

Beginner
Key Points装完只需关注三个变量:`GOROOT`(安装位置)、`GOPATH`(工作区)、`GOPROXY`(模块代理)。

安装

Bash
# macOS
brew install go

# Linux(也可用包管理器)
wget https://go.dev/dl/go1.22.8.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.8.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin

# Windows
winget install GoLang.Go

验证

Bash
go version
go env GOROOT GOPATH GOPROXY
Output
go version go1.22.8 windows/amd64
C:\Program Files\Go
C:\Users\Administrator\go
https://proxy.golang.org,direct

国内必配:模块代理

Bash
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOSUMDB=off
go env -w GO111MODULE=on

Without a proxy, go get frequently times out on GitHub. direct is the fallback. GOSUMDB=off disables the checksum database (often unreachable in China); keep it on in production.

三个目录

VariableMeaningDefault
GOROOTGo 的安装目录随安装包
GOPATH工作区,第三方包与 bin 在此~/go
GOMODCACHE模块缓存$GOPATH/pkg/mod

第一个项目

Bash
mkdir hello && cd hello
go mod init example.com/hello
Go
package main

import "fmt"

func main() {
	fmt.Println("你好,Go")
}
Bash
go run .
go build -o hello
./hello
Output
你好,Go
你好,Go
The module path in go mod init need not exist, but use a domain you control (github.com/you/project); otherwise publishing will conflict later.

Friends & Partners