全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-14 7 分钟 ✍️ juanwangdev

Go io包

Go标准库io定义核心I/O接口和实用函数。

核心接口

io.Reader接口

Go
type Reader interface {
    Read(p []byte) (n int, err error)
}

// Read读取数据到p,返回读取字节数和错误
// err为io.EOF表示读取结束

io.Writer接口

Go
type Writer interface {
    Write(p []byte) (n int, err error)
}

// Write写入p数据,返回写入字节数和错误

Reader和Writer是Go I/O的核心接口,大多数类型都实现它们。

实现Reader的类型

Go
// 标准库实现Reader的类型
os.File          // 文件
bytes.Buffer     // 字节缓冲
strings.Reader   // 字符串读取器
net.Conn         // 网络连接
http.Request.Body // HTTP请求体

实现Writer的类型

Go
// 标准库实现Writer的类型
os.File          // 文件
bytes.Buffer     // 字节缓冲
http.ResponseWriter // HTTP响应
net.Conn         // 网络连接

常用函数

io.Copy

Go
// 从Reader复制到Writer
src := strings.NewReader("hello world")
dst := &bytes.Buffer{}

n, err := io.Copy(dst, src)
// n = 11, dst内容 = "hello world"

// 常用于文件复制
io.Copy(dstFile, srcFile)

io.CopyN

Go
// 复制指定字节数
src := strings.NewReader("hello world")
dst := &bytes.Buffer{}

n, _ := io.CopyN(dst, src, 5)
// dst内容 = "hello"

io.ReadAll

Go
// 读取全部内容
body, _ := io.ReadAll(resp.Body)
// body = []byte全部响应内容

// 读取文件全部内容
data, _ := io.ReadAll(file)

ReadAll会读取直到EOF,注意内存消耗。

io.ReadAtLeast

Go
// 至少读取指定字节数
buf := make([]byte, 10)
n, _ := io.ReadAtLeast(reader, buf, 5)
// 至少读取5字节到buf

io.LimitReader

Go
// 限制读取字数
reader := strings.NewReader("hello world")
limited := io.LimitReader(reader, 5)

data, _ := io.ReadAll(limited)
// data = "hello"(只读取5字节)

多Reader组合

io.MultiReader

Go
// 多个Reader合并
r1 := strings.NewReader("hello")
r2 := strings.NewReader(" ")
r3 := strings.NewReader("world")

mr := io.MultiReader(r1, r2, r3)
data, _ := io.ReadAll(mr)
// data = "hello world"

io.TeeReader

Go
// 读取同时写入
src := strings.NewReader("hello")
dst := &bytes.Buffer{}

tee := io.TeeReader(src, dst)
data, _ := io.ReadAll(tee)

// data = "hello", dst也写入"hello"

多Writer组合

io.MultiWriter

Go
// 多个Writer同时写入
w1 := &bytes.Buffer{}
w2 := &bytes.Buffer{}

mw := io.MultiWriter(w1, w2)
mw.Write([]byte("hello"))

// w1和w2都写入"hello"

Pipe管道

io.Pipe

Go
// 创建同步管道
r, w := io.Pipe()

// 写入端
go func() {
    w.Write([]byte("hello"))
    w.Close()
}()

// 读取端
data, _ := io.ReadAll(r)
// data = "hello"

// Pipe是同步的,Write阻塞等待Read

SectionReader

io.SectionReader

Go
// 读取部分内容
reader := strings.NewReader("hello world")

// 从位置2开始读取5字节
section := io.NewSectionReader(reader, 2, 5)
data, _ := io.ReadAll(section)
// data = "llo w"

空操作

io.Discard

Go
// 丢弃写入数据(空Writer)
io.Copy(io.Discard, reader)  // 读取但不保存

// 用于丢弃不需要的数据

io.EOF

Go
// EOF错误表示读取结束
var buf [4]byte
for {
    n, err := reader.Read(buf[:])
    if err == io.EOF {
        break  // 读取结束
    }
    // 处理数据
}

缓冲读写

bufio.Reader

Go
import "bufio"

// 带缓冲的Reader
r := bufio.NewReader(reader)

// 按行读取
line, _ := r.ReadString('\n')

// 按字节读取
b, _ := r.ReadByte()

// 读取指定分隔符
s, _ := r.ReadBytes(',')

bufio.Writer

Go
// 带缓冲的Writer
w := bufio.NewWriter(writer)

w.WriteString("hello")
w.Flush()  // 必须刷新缓冲区

io/ioutil包

Go
import "io/ioutil"

// Go 1.16后推荐使用io/os包

// 读取文件(旧)
data, _ := ioutil.ReadFile("file.txt")

// 读取全部(新)
data, _ := io.ReadAll(file)

// 写入文件(旧)
ioutil.WriteFile("file.txt", data, 0644)

// 写入文件(新)
os.WriteFile("file.txt", data, 0644)

常用函数表

函数用途返回值
Copy复制数据n, err
CopyN复制指定字节n, err
ReadAll读取全部[]byte, err
LimitReader限制读取Reader
MultiReader合合ReaderReader
MultiWriter合合WriterWriter
TeeReader读取同时写Reader
Pipe创建管道Reader, Writer

要点总结

  • Reader接口定义Read方法
  • Writer接口定义Write方法
  • Copy从Reader复制到Writer
  • ReadAll读取全部内容
  • MultiReader合并多个Reader
  • MultiWriter同时写入多个目标
  • TeeReader读取同时写入
  • LimitReader限制读取字数
  • Pipe创建同步读写管道
  • io.EOF表示读取结束
  • io.Discard丢弃写入数据
  • bufio提供缓冲读写功能

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go http包
下一篇 → Go log包
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库