文章

阶段2 标准库全貌 - 代码实例集

阶段 2 标准库全貌 · 代码实例集

覆盖学习计划 P0→P2 的常用标准库,每个库给核心可运行实例。 深入讲解见 03-标准库/*.md(15 章参考手册)。本集侧重「看代码就会用」。


P0(日常 80% 场景)

fmt — 格式化 I/O

fmt.Printf("%d %s %.2f\n", 1, "go", 3.14159) // 1 go 3.14
fmt.Sprintf("id=%d", 7)                       // 返回字符串
// %v 任意值, %+v 带字段名, %#v Go 语法, %T 类型

os — 操作系统交互

import "os"
os.Getenv("PATH")            // 读环境变量
os.Setenv("KEY", "val")
os.Args                    // 命令行参数
os.Exit(1)                 // 退出码
os.Stdout.Write([]byte("hi"))
// 文件见 io/文件系统章节

strings — 字符串处理

import "strings"
strings.Contains("golang", "go")     // true
strings.Split("a,b,c", ",")          // [a b c]
strings.Join([]string{"a","b"}, "-") // a-b
strings.ReplaceAll("foo", "o", "0")  // f00
strings.TrimSpace("  hi  ")          // hi
strings.HasPrefix("golang", "go")    // true

errors — 错误处理

import "errors"
var ErrNotFound = errors.New("not found")
if err := do(); err != nil { /* 处理 */ }

// 包装:%w 保留原错误链,errors.Is / errors.As 可解包
err := fmt.Errorf("db query: %w", ErrNotFound)
errors.Is(err, ErrNotFound) // true

sync — 见阶段1 01-并发地基 第 4 节(Mutex/RWMutex/WaitGroup/Once/Pool/atomic)

context — 见阶段1 01-并发地基 第 5 节

net/http — HTTP 服务与客户端

import "net/http"

// 服务端
func main() {
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("hello"))
	})
	http.ListenAndServe(":8080", nil)
}

// 客户端
resp, _ := http.Get("https://example.com")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

encoding/json — 序列化

import "encoding/json"

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age,omitempty"`
}
u := User{Name: "xu", Age: 30}
b, _ := json.Marshal(u)             // {"name":"xu","age":30}
var u2 User
json.Unmarshal(b, &u2)              // 反序列化到指针

注意:只有导出字段(首字母大写)才能序列化。


P1(服务开发必备)

io — 读写抽象

import (
	"io"
	"strings"
)
r := strings.NewReader("hello")
buf := make([]byte, 3)
for {
	n, err := r.Read(buf) // 每次读 3 字节
	if n > 0 { print(string(buf[:n])) }
	if err == io.EOF { break }
}
io.Copy(dst, src) // 通用拷贝

bytes — 字节切片工具

import "bytes"
var buf bytes.Buffer
buf.WriteString("hello ")
buf.WriteString("world")
buf.Bytes()        // []byte
buf.String()       // string
bytes.Contains([]byte("abc"), []byte("b")) // true

bufio — 带缓冲 I/O

import "bufio"
w := bufio.NewWriter(os.Stdout)
w.WriteString("buffered\n")
w.Flush() // 必须 flush 才真正写出
r := bufio.NewScanner(os.Stdin)
for r.Scan() { fmt.Println(r.Text()) }

time — 时间处理

import "time"
now := time.Now()
later := now.Add(2 * time.Hour)
diff := later.Sub(now)         // 2h0m0s
time.Sleep(100 * time.MtSecond)
t := time.Date(2026, 8, 5, 0, 0, 0, 0, time.UTC)
fmt.Println(t.Weekday())        // Wednesday
// 格式化用固定参考时间 2006-01-02 15:04:05
t.Format("2006-01-02 15:04:05")

flag — 命令行参数

import "flag"
name := flag.String("name", "world", "your name")
flag.Parse()
fmt.Println("hello", *name) // go run main.go -name=xu

testing — 表驱动测试

import "testing"
func TestAdd(t *testing.T) {
	cases := []struct{ a, b, want int }{
		{1, 2, 3}, {0, 0, 0}, {-1, 1, 0},
	}
	for _, c := range cases {
		if got := c.a + c.b; got != c.want {
			t.Errorf("(%d+%d)=%d, want %d", c.a, c.b, got, c.want)
		}
	}
}

log — 日志

import "log"
log.Println("info")
log.Printf("value=%d", 42)
log.SetPrefix("[care-mate] ")
// 生产用更高级的日志库(zap/slog),标准库 log 够轻量场景

P2(进阶与调优)

crypto — 哈希与加密

import (
	"crypto/sha256"
	"crypto/md5"
	"fmt"
)
h := sha256.Sum256([]byte("secret"))
fmt.Printf("%x\n", h) // 十六进制
// 加密(AES)见 03-标准库/09-加密与安全.md

encoding — 其他格式

import (
	"encoding/xml"
	"encoding/csv"
)
// XML 序列化
type Note struct {
	XMLName xml.Name `xml:"note"`
	Body    string   `xml:"body"`
}
b, _ := xml.Marshal(Note{Body: "hi"})

// CSV 读取
f, _ := os.Open("data.csv")
defer f.Close()
r := csv.NewReader(f)
records, _ := r.ReadAll() // [][]string

net — 底层网络

import "net"
// 监听 TCP
ln, _ := net.Listen("tcp", ":9000")
conn, _ := ln.Accept()
conn.Write([]byte("hi"))
// DNS 解析:net.LookupHost("example.com")

sort — 排序

import "sort"
nums := []int{3, 1, 2}
sort.Ints(nums)              // [1 2 3]
sort.Slice([]User{}, func(i, j int) bool { return users[i].Age < users[j].Age })

reflect — 见阶段3 03-泛型与接口 第 3 节

runtime — 运行时信息

import "runtime"
runtime.GC()                  // 手动触发 GC(通常不需要)
runtime.NumGoroutine()       // 当前 goroutine 数
runtime.Goexit()             // 立即终止当前 goroutine

pprof — 性能剖析

import _ "net/http/pprof" // 匿名导入,自动注册 /debug/pprof
// 启动 http 服务后访问:
//   go tool pprof http://localhost:8080/debug/pprof/heap
//   go tool pprof http://localhost:8080/debug/pprof/profile?seconds=30
// 详见阶段4 `04-性能与工程化` 第 1 节

自测题

  1. JSON 序列化时,为什么字段名首字母必须大写?怎么自定义 JSON key?
  2. errors.Is 和直接 == 比较错误有什么区别?
  3. bufio.Writer 为什么必须 Flush()
  4. time 格式化的参考时间为什么是 2006-01-02 15:04:05
  5. 下面是一个常见 bug,为什么读不全?怎么修?
buf := make([]byte, 4)
n, _ := r.Read(buf)
fmt.Println(string(buf[:n])) // 大文件只打印前 4 字节

03-标准库/*.md 对应章节深入。卡住就问。