Skip to content
Go
Go 标准库速览

Go 标准库速览

Go 标准库核心包的分类速查与关键 API 指引。不追求详尽,而是提供一个按需时知道"该去哪找"的地图。


1. 输入输出

包 用途 核心类型/函数
fmt 格式化输入输出 Printf, Sprintf, Fprintf, Scanf, Errorf
io 基本 IO 接口 Reader, Writer, Closer, ReadAll, Copy, Pipe
os OS 功能(文件/进程/环境) Open, Create, ReadFile, WriteFile, Remove, MkdirAll, Getenv, Exit, Stdin/Stdout/Stderr
bufio 缓冲 IO NewReader, NewWriter, NewScanner
bytes 字节切片操作 Buffer, Reader, Contains, Split, Join, Equal, CutLast(Go 1.27)
strings 字符串操作 Builder, Reader, Contains, Split, Join, Replace, Trim, ToLower, CutLast(Go 1.27)
path/filepath 文件路径操作 Join, Split, Ext, Base, Dir, Abs, Walk, Glob
path URL 路径操作 Join, Split, Ext, Base, Dir(斜杠分隔,不处理平台差异)

io 接口速查

// 核心接口(组合自这些基本接口)
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
type Closer interface { Close() error }
type Seeker interface { Seek(offset int64, whence int) (int64, error) }

// 组合接口
type ReadWriter interface { Reader; Writer }
type ReadCloser interface { Reader; Closer }
type WriteCloser interface { Writer; Closer }
type ReadWriteCloser interface { Reader; Writer; Closer }
type ReadSeeker interface { Reader; Seeker }

便捷读写函数(Go 1.16+)

// os.ReadFile / os.WriteFile:简化全部读入/写出
data, err := os.ReadFile("config.yaml")
err := os.WriteFile("output.txt", data, 0644)

// io.ReadAll:全部读入
data, err := io.ReadAll(reader)

// io.Copy:流式复制
written, err := io.Copy(dst, src)

// io.NopCloser:给 Reader 包装一个空 Close
r := io.NopCloser(strings.NewReader("data"))

// io.TeeReader:读取时同时写入另一个 Writer
tee := io.TeeReader(reader, writer)

CutLast:在最后一个分隔符处切分(Go 1.27)

老写法要 LastIndex 再手动切两刀,strings.CutLast / bytes.CutLast 一步到位:

before, after, found := strings.CutLast("a.b.c", ".")
// before="a.b", after="c", found=true
// sep 不存在时返回 (s, "", false),与 Cut 的约定一致

适合从 host:port:seq 这类串里取最后一段的常见套路。它是三返回值函数,常规调用要完整解构接收,不能当单值表达式嵌进别的调用里。


2. 编码与序列化

包 用途 核心函数
encoding/json JSON 编解码 Marshal, Unmarshal, NewEncoder, NewDecoder
encoding/xml XML 编解码 Marshal, Unmarshal
encoding/csv CSV 读写 NewReader, NewWriter
encoding/base64 Base64 编解码 StdEncoding.Encode, Decode
encoding/hex 十六进制编解码 EncodeToString, DecodeString
encoding/binary 二进制编解码 Read, Write, BigEndian, LittleEndian
encoding/gob Go 二进制格式 NewEncoder, NewDecoder
// JSON 常用模式
type Config struct {
    Host string `json:"host"`
    Port int    `json:"port,omitempty"`
    Mode string `json:"mode,omitempty"`
}

data, _ := json.Marshal(config)                    // 结构体 → JSON
json.Unmarshal(data, &config)                      // JSON → 结构体

// json.NewDecoder:流式解码(http body、大文件)
decoder := json.NewDecoder(resp.Body)
decoder.Decode(&config)

// 美化输出
data, _ := json.MarshalIndent(config, "", "  ")

3. 网络与 HTTP

包 用途 核心类型/函数
net 网络基础 Dial, Listen, TCPConn, UDPConn, Resolver
net/http HTTP 客户端/服务端 Get, Post, Client, Server, Handler, HandleFunc, ListenAndServe, NewRequestWithContext;Go 1.27 新增 Server.MaxHeaderValueCount(限制接受的 header 值条数,不设用 DefaultMaxHeaderValueCount=500),HTTP/2 服务端开始接受客户端优先级信号(RFC 9218,Server.DisableClientPriority 可退回轮询)
net/url URL 解析 Parse, Values, URL;Go 1.27 新增 URL.Clone / Values.Clone 深拷贝
net/mail 邮件地址解析 ParseAddress, ParseDate
crypto/tls TLS/SSL Config, Listen, Dial(Config.Rand 自 Go 1.27 起弃用:生产环境留 nil,测试注入随机源改用 testing/cryptotest.SetGlobalRandom)
net/http/httptest HTTP 测试 NewServer, NewRecorder, NewTestServer(Go 1.27,内存假网络)
net/http/httputil HTTP 工具 ReverseProxy, DumpRequest
// 基本 HTTP Server
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(response)
})
http.ListenAndServe(":8080", nil)

// HTTP Client(Go 1.16+ 推荐用 context)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil { return err }
defer resp.Body.Close()

body, _ := io.ReadAll(resp.Body)

4. 时间与日期

包 用途 核心函数/类型
time 时间处理 Now, Date, Parse, Since, Until, After, Sleep, Ticker, Timer, Duration
t := time.Now()
t.Format("2006-01-02 15:04:05")   // Go 的参考时间是 Mon Jan 2 15:04:05 MST 2006
t, _ = time.Parse("2006-01-02", "2024-12-31")

// Duration 运算
time.Sleep(100 * time.Millisecond)
d := time.Since(t)                // 时间间隔

// Timer / Ticker
timer := time.NewTimer(5 * time.Second)
<-timer.C                         // 等待 5 秒

ticker := time.NewTicker(1 * time.Second)
for t := range ticker.C { ... }   // 每秒触发
ticker.Stop()

// 定时执行:Tick 适合"与进程同寿命"的全局周期任务
go func() {
    for range time.Tick(1 * time.Minute) {
        doTask()
    }
}()

陷阱:

  • 格式参照时间 Mon Jan 2 15:04:05 MST 2006(2006-01-02 15:04:05),不是任意日期
  • time.Tick 无法主动停止(要可控周期用 NewTicker + Stop)。“忘记 Stop 必泄漏"的旧说法只对 Go 1.23 之前成立——1.23 起完全不再被引用的 Timer/Ticker 会被 GC 回收、也无需排空通道(Go 1.27 已移除 asynctimerchan 回退开关,新语义是唯一行为)。只要 goroutine 还持有 Tick 的通道在 range,它就照常在进程存活期内周期运行
  • Timer 复用直接 Reset(1.23+ 无需先手动收掉旧值)

5. 并发与同步

包 用途 核心类型/函数
sync 基本同步原语 Mutex, RWMutex, WaitGroup, Once, Map, Pool, Cond
sync/atomic 原子操作 Int64, Uint64, Pointer, Value(Go 1.19+ 类型)
context 请求范围控制 WithCancel, WithTimeout, WithDeadline, WithValue

详见 08-并发编程。

注意:排查 goroutine 泄漏时,runtime/pprof 的 goroutineleak profile 在 Go 1.26 还只是实验(GOEXPERIMENT=goroutineleakprofile,该开关 1.27 已删除),1.27 正式可用:pprof.Lookup("goroutineleak") 或 HTTP 端点 /debug/pprof/goroutineleak。它报告"永久阻塞在 channel、sync.Mutex 等同步原语上、不可能再被唤醒"的 goroutine,本地 1.27 实测 Lookup 返回非 nil。


6. 测试

包 用途 核心内容
testing 单元测试 *testing.T, *testing.B, *testing.F(Fuzz,Go 1.18+)
testing/fstest 文件系统测试 MapFS
testing/iotest IO 测试工具 ErrReader, OneByteReader
testing/quick 随机测试 Check, Config
net/http/httptest HTTP 测试 NewServer, NewRecorder, NewTestServer(Go 1.27)
testing/synctest 并发/网络测试气泡(Go 1.25 正式) Test, Wait, Sleep(Sleep 为 Go 1.27 新增)
// 单元测试
func TestAdd(t *testing.T) {
    got := Add(1, 2)
    want := 3
    if got != want {
        t.Errorf("Add(1, 2) = %d, want %d", got, want)
    }
}

// 表驱动测试(Go 惯用法)
func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b, want int
    }{
        {"positive", 1, 2, 3},
        {"negative", -1, -2, -3},
        {"zero", 0, 0, 0},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Add(tt.a, tt.b); got != tt.want {
                t.Errorf("got %d, want %d", got, tt.want)
            }
        })
    }
}

// 基准测试
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}

// Fuzz 测试(Go 1.18+)
func FuzzAdd(f *testing.F) {
    f.Add(1, 2)
    f.Fuzz(func(t *testing.T, a, b int) {
        Add(a, b)
    })
}

// Go 1.27:httptest.NewTestServer 跑在内存假网络上,专为 testing/synctest 气泡设计,
// 不起真实端口、不吃真实时钟,用法与 NewServer 一致(srv.URL / srv.Client())
func TestFetch(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        srv := httptest.NewTestServer(t, handler)      // handler 传 nil 则一律回 500
        resp, err := srv.Client().Get(srv.URL)
        if err != nil {
            t.Fatal(err)
        }
        defer resp.Body.Close()
    })
}

// 运行
// go test ./...                      运行所有测试
// go test -run TestAdd              运行指定测试
// go test -bench=. -benchmem        基准测试 + 内存分析
// go test -fuzz=FuzzAdd             运行 fuzz 测试
// go test -coverprofile=cover.out   生成覆盖率
// go tool cover -html=cover.out     覆盖率可视化

7. 错误与日志

包 用途 核心内容
errors 错误处理 New, Is, As, Unwrap, Join(Go 1.20+)
log 标准日志 Printf, Fatalf, Panicf, SetFlags, New
log/slog 结构化日志(Go 1.21+) Info, Debug, Error, With, NewJSONHandler
fmt 格式化 Errorf("%w", err)
// slog 结构化日志(Go 1.21+)
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("request processed",
    slog.String("method", "GET"),
    slog.Int("status", 200),
    slog.Duration("latency", 10*time.Millisecond),
)
// {"time":"2024-01-01T00:00:00Z","level":"INFO","msg":"request processed","method":"GET","status":200,"latency":"10ms"}

详见 07-错误处理。


8. 数学与随机

包 用途 核心函数
math 数学函数 Abs, Max, Min, Pow, Sqrt, Sin, Cos, Pi
math/rand 伪随机数 Intn, Float64, Shuffle(Go 1.20+ 自动随机种子)
math/rand/v2 新版伪随机(Go 1.22+) IntN, N;Go 1.27 起 N 也有方法版 (*Rand).N
math/big 大数 Int, Rat, Float
// Go 1.20+:无需手动 Seed
n := rand.Intn(100)               // 0 ≤ n < 100
f := rand.Float64()               // 0.0 ≤ f < 1.0

// 加密安全的随机数
import "crypto/rand"
b := make([]byte, 32)
rand.Read(b)

// math/rand/v2(Go 1.22+):新代码推荐;Go 1.27 起泛型函数 N 同时提供方法版 (*Rand).N
vr := rand.New(rand.NewPCG(1, 2))
vr.IntN(100)              // int,0 ≤ n < 100
u8 := vr.N[uint8](7)      // 方法版 N,任意整数类型按需(n ≤ 0 会 panic)
_ = u8

9. 反射、不安全与类型

包 用途
reflect 反射:运行时类型/值检查与操作
unsafe 不安全操作:指针转换、内存布局
cmp 比较工具(Go 1.21+):Ordered 约束、Compare, CompareEqual, Or
slices 切片泛型工具(Go 1.21+):Sort, Contains, Clone, Delete
maps Map 泛型工具(Go 1.21+):Equal, Clone, Copy(1.23 起 Keys/Values 返回迭代器)

10. 压缩与归档

包 用途
compress/gzip Gzip 压缩/解压
compress/zlib Zlib 压缩/解压
archive/zip Zip 归档
archive/tar Tar 归档
// gzip 写入
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
w.Write([]byte("hello"))
w.Close()

// gzip 读取
r, _ := gzip.NewReader(&buf)
data, _ := io.ReadAll(r)
fmt.Println(string(data))          // hello

11. 哈希与加密

包 用途
crypto/md5 MD5 哈希(仅用于非安全场景)
crypto/sha1 SHA1 哈希
crypto/sha256 SHA256 哈希
crypto/hmac HMAC
crypto/aes AES 加密
crypto/rand 加密安全随机数
crypto/tls TLS 协议
hash 哈希接口
// SHA256
h := sha256.Sum256([]byte("hello"))
fmt.Printf("%x\n", h)

// 流式
hasher := sha256.New()
hasher.Write([]byte("hello"))
hasher.Write([]byte(" world"))
hash := hasher.Sum(nil)

12. 数据库(database/sql)

import (
    "database/sql"
    _ "github.com/lib/pq"          // 仅执行 init() 注册驱动
)

db, err := sql.Open("postgres", dsn)
defer db.Close()

// 查询单行
var name string
err = db.QueryRowContext(ctx, "SELECT name FROM users WHERE id=$1", id).Scan(&name)

// 查询多行
rows, err := db.QueryContext(ctx, "SELECT id, name FROM users")
defer rows.Close()
for rows.Next() {
    var id int
    var name string
    rows.Scan(&id, &name)
}

// 事务
tx, err := db.BeginTx(ctx, nil)
_, err = tx.ExecContext(ctx, "UPDATE users SET name=$1 WHERE id=$2", name, id)
tx.Commit()  // 或 tx.Rollback()

13. Go 1.21+ 新增包速查

包 版本 用途
slices Go 1.21 泛型切片工具(Contains, Sort, Clone, Delete…)
maps Go 1.21 泛型 map 工具(Equal, Clone, Copy, DeleteFunc…)
cmp Go 1.21 比较工具(Ordered, Or, Compare)
log/slog Go 1.21 结构化日志
iter Go 1.23 迭代器类型(Seq/Seq2)+ Pull 转换
unique Go 1.23 值驻留/规范化(Make[T]/Handle[T])
structs Go 1.23 HostLayout 标记类型
crypto/mlkem Go 1.24 后量子密钥交换 ML-KEM(FIPS 203);Go 1.27 增 MLKEM1024(把它加入 Config.CurvePreferences 启用)
crypto/hkdf Go 1.24 HMAC 密钥派生(RFC 5869)
crypto/pbkdf2 Go 1.24 密码密钥派生(RFC 8018)
crypto/sha3 Go 1.24 SHA-3 / SHAKE / cSHAKE(FIPS 202)
weak Go 1.24 弱指针(不阻止 GC 回收)
crypto/hpke Go 1.26 HPKE 混合加密(RFC 9180),含后量子混合 KEM
crypto/mldsa Go 1.27 后量子签名 ML-DSA(FIPS 204,MLDSA44/65/87)
uuid Go 1.27 UUID 生成与解析(RFC 9562)。顶层 import 路径 uuid,不是 crypto/rand/uuid;New/NewV4/NewV7 直接返回 UUID(无 error),Nil()/Max() 是函数,Parse(s) (UUID, error) / MustParse;UUID 为 [16]byte 可比较。低于 go1.27 的模块里使用会被 go test 默认的 stdversion 检查拦截(报 uuid.New requires go1.27 or later)
sync/atomic (类型) Go 1.19 原子类型(Int64, Bool, Pointer…)
embed Go 1.16 文件嵌入
io/fs Go 1.16 文件系统接口
testing/fstest Go 1.16 文件系统测试

Go 1.24 实验 → 1.25 正式

包 版本 用途
testing/synctest Go 1.24 实验 → 1.25 正式 并发测试隔离气泡 + 虚拟时钟。现行 API 是 Test(t, f) / Wait / Sleep(Sleep 为 1.27 新增,等于 time.Sleep+Wait);1.24 实验版的旧 API Run 已移除,go1.27 下不存在

Go 1.25 实验 → 1.27 正式

包 版本 用途
encoding/json/v2 Go 1.25 实验(jsonv2)→ 1.27 正式 JSON v2 引擎;1.27 起 encoding/json 默认由 v2 支撑(过渡期回退 GOEXPERIMENT=nojsonv2),解码显著提速但校验更严格
encoding/json/jsontext Go 1.27 正式 JSON Token 底层编码层(v2 的地基)

Go 1.26+ 实验

包/标志 用途
simd(可移植向量类型) 1.27 新增:与向量宽度无关的 SIMD 类型,各架构可用(GOEXPERIMENT=simd)
simd/archsimd (GOEXPERIMENT=simd) 架构专用 SIMD:1.26 起 amd64;1.27 扩展 arm64 Neon / wasm 128-bit
runtime/secret (GOEXPERIMENT=runtimesecret) 加密临时值安全擦除(Go 1.26 引入,仍为实验)

此外,Go 1.27 对既有包也有一次系统性升级:unicode 及其在全系统的支持从 Unicode 15 升到 Unicode 17,新分配的字符在 unicode.Is 系列判断与文本处理中即刻可用。


14. 快速选包指南

场景                       → 应该用的包
──────────────────────────────────────────
读文件全部内容             → os.ReadFile
逐行读文件                 → bufio.NewScanner
写文件                     → os.WriteFile
格式化字符串               → fmt.Sprintf
JSON 编解码                → encoding/json
HTTP 客户端                → net/http
HTTP 服务器                 → net/http
URL 解析                   → net/url
文件路径拼接               → path/filepath(OS 路径)/ path(URL 路径)
时间格式化                 → time.Format("2006-01-02 15:04:05")
计时/超时                  → time.Timer / time.After / context.WithTimeout
并发同步                   → sync.Mutex / sync.WaitGroup
协程间通信                 → channel
请求取消/超时              → context.WithCancel / context.WithTimeout
单次执行                   → sync.Once
计数等待                   → sync.WaitGroup
拷贝/全部读入 Reader       → io.Copy / io.ReadAll
字节拼接                   → bytes.Buffer / strings.Builder
按最后一个分隔符切分       → strings.CutLast / bytes.CutLast(Go 1.27,替代 LastIndex 套路)
错误包装                   → fmt.Errorf("%w", err)
错误判断                   → errors.Is / errors.As
模糊测试                   → testing.F(Go 1.18+)
HTTP/网络代码单测          → httptest.NewServer;Go 1.27 配 testing/synctest 用 NewTestServer(内存假网络)
排查 goroutine 泄漏        → pprof.Lookup("goroutineleak")(Go 1.27 转正,也挂在 /debug/pprof/ 下)
正则匹配(RE2 无回溯)     → regexp(Compile 有成本,编译一次全局复用)
哈希/消息认证/AEAD         → crypto/sha256 / crypto/hmac / crypto/cipher(AES-GCM,nonce 绝不重用)
运行外部命令               → os/exec(别过 sh -c;管道与 Wait 的顺序见 go-std 的 os-exec 篇)
信号与优雅关停             → os/signal.NotifyContext + http Server.Shutdown
数据库访问                 → database/sql(*sql.DB 是连接池不是连接;生产必设 SetMaxOpenConns)
UUID                       → uuid(Go 1.27;DB 主键优先 NewV7,见 go-std/01/uuid.md)
压缩与归档                 → compress/gzip + archive/tar(tar.gz)/ archive/zip(解压先防 zip-slip)