跳到主要内容

Go 标准库概览

Go 语言拥有一个强大且丰富的标准库,涵盖了网络编程、数据处理、加密、文本处理等多个领域。掌握标准库是成为高效 Go 开发者的关键。

标准库的特点

Go 标准库的设计遵循以下原则:

  1. 简洁实用:API 设计简洁,功能实用,避免过度设计
  2. 文档完善:每个包都有详细的文档说明
  3. 跨平台:大部分包都支持跨平台使用
  4. 性能优秀:经过充分优化,性能可靠

标准库分类

基础包

包名说明
fmt格式化输入输出
os操作系统功能
io基本输入输出接口
strings字符串操作
strconv字符串转换
time时间和日期

网络包

包名说明
net网络编程基础
net/httpHTTP 客户端和服务端
net/urlURL 解析
net/rpcRPC 调用

数据处理包

包名说明
encoding/jsonJSON 编解码
encoding/xmlXML 编解码
encoding/csvCSV 文件处理
encoding/base64Base64 编解码

加密包

包名说明
crypto/md5MD5 哈希
crypto/sha256SHA256 哈希
crypto/aesAES 加密
crypto/rand加密安全随机数

并发包

包名说明
sync同步原语(Mutex、WaitGroup 等)
sync/atomic原子操作
context上下文管理

文件系统包

包名说明
os文件操作
path/filepath文件路径操作
io/ioutil文件读写工具(已废弃,使用 io 和 os 替代)

查看标准库文档

在线文档

访问 Go 官方文档网站:https://pkg.go.dev/std

本地文档

使用 Go 工具查看本地文档:

# 启动本地文档服务器
go doc -http=:6060

# 在浏览器中访问 http://localhost:6060

命令行查看

# 查看包文档
go doc fmt

# 查看具体函数
go doc fmt.Println

# 查看完整文档
go doc -all fmt

常用包快速参考

fmt 包

import "fmt"

// 打印
fmt.Println("Hello") // 换行打印
fmt.Printf("Name: %s\n", name) // 格式化打印
fmt.Sprint("Hello") // 返回字符串
fmt.Sprintf("Age: %d", age) // 格式化返回字符串

// 格式化动词
// %v - 默认格式
// %s - 字符串
// %d - 整数
// %f - 浮点数
// %t - 布尔值
// %T - 类型
// %x - 十六进制

strings 包

import "strings"

str := "Hello, World!"

// 查找
strings.Contains(str, "World") // true
strings.HasPrefix(str, "Hello") // true
strings.HasSuffix(str, "!") // true
strings.Index(str, "World") // 7

// 转换
strings.ToUpper(str) // "HELLO, WORLD!"
strings.ToLower(str) // "hello, world!"
strings.Title(str) // "Hello, World!"

// 分割和连接
strings.Split("a,b,c", ",") // ["a", "b", "c"]
strings.Join([]string{"a", "b"}, "-") // "a-b"

// 替换和修剪
strings.Replace(str, "World", "Go", 1) // "Hello, Go!"
strings.TrimSpace(" hello ") // "hello"
strings.Trim(str, "!") // "Hello, World"

strconv 包

import "strconv"

// 字符串转数字
n, _ := strconv.Atoi("123") // 123
f, _ := strconv.ParseFloat("3.14", 64) // 3.14
b, _ := strconv.ParseBool("true") // true

// 数字转字符串
s1 := strconv.Itoa(123) // "123"
s2 := strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14"
s3 := strconv.FormatBool(true) // "true"

time 包

import "time"

// 当前时间
now := time.Now()

// 格式化
fmt.Println(now.Format("2006-01-02 15:04:05"))

// 解析
t, _ := time.Parse("2006-01-02", "2024-01-01")

// 时间运算
tomorrow := now.Add(24 * time.Hour)
duration := now.Sub(t)

// 定时器
timer := time.NewTimer(time.Second)
<-timer.C

// 延迟执行
time.Sleep(time.Second)

os 包

import "os"

// 环境变量
os.Getenv("PATH") // 获取环境变量
os.Setenv("KEY", "value") // 设置环境变量
os.Environ() // 所有环境变量

// 文件操作
file, _ := os.Open("test.txt") // 打开文件
file, _ := os.Create("test.txt") // 创建文件
os.Remove("test.txt") // 删除文件
os.Rename("old.txt", "new.txt") // 重命名

// 目录操作
os.Mkdir("dir", 0755) // 创建目录
os.MkdirAll("a/b/c", 0755) // 创建多级目录
os.Remove("dir") // 删除空目录
os.RemoveAll("dir") // 删除目录及内容

// 文件信息
info, _ := os.Stat("test.txt")
fmt.Println(info.Name(), info.Size(), info.IsDir())

math 包

import "math"

// 常量
math.Pi // π
math.E // e

// 基本运算
math.Abs(-5) // 5
math.Sqrt(16) // 4
math.Pow(2, 3) // 8
math.Mod(10, 3) // 1

// 取整
math.Floor(3.7) // 3
math.Ceil(3.2) // 4
math.Round(3.5) // 4

// 三角函数
math.Sin(math.Pi / 2) // 1
math.Cos(0) // 1

// 最值
math.Max(1, 2) // 2
math.Min(1, 2) // 1

标准库使用建议

1. 优先使用标准库

Go 标准库功能完善且经过充分测试,在大多数情况下可以直接使用,无需引入第三方库。

// 推荐:使用标准库
import "encoding/json"

// 不推荐:除非有特殊需求
import "github.com/xxx/json"

2. 注意包的废弃

部分包可能被废弃,应使用替代方案:

// 已废弃
import "io/ioutil"

// 使用替代方案
import (
"io"
"os"
)

// ioutil.ReadFile -> os.ReadFile
// ioutil.WriteFile -> os.WriteFile
// ioutil.ReadDir -> os.ReadDir
// ioutil.TempDir -> os.MkdirTemp
// ioutil.TempFile -> os.CreateTemp

3. 使用 internal 包

标准库中的 internal 包是内部实现,不应直接使用:

// 不要使用
import "net/http/internal"

4. 理解接口设计

标准库大量使用接口,理解这些接口可以更好地使用标准库:

// io.Reader 接口
type Reader interface {
Read(p []byte) (n int, err error)
}

// io.Writer 接口
type Writer interface {
Write(p []byte) (n int, err error)
}

// 任何实现了这些接口的类型都可以使用
var r io.Reader = strings.NewReader("hello")
var w io.Writer = os.Stdout

小结

本章介绍了 Go 标准库的整体结构和常用包的基本用法:

  1. 标准库分类:基础包、网络包、数据处理包、加密包、并发包等
  2. 查看文档:在线文档、本地文档、命令行工具
  3. 常用包:fmt、strings、strconv、time、os、math
  4. 使用建议:优先标准库、注意废弃、理解接口

下一步