实现说明
MultiReader 与 LimitReader 组合读取可以归结为函数 main。
err 在 1 处被测试,非 nil 就以 panic(err) 中止运行。
使用要点
- 示例不返回错误——任何非 nil 的
err都会让运行立即结束。
常见问题
错误处理是什么风格?
失败路径是 panic(err)——检测到的问题让运行终止,而不是被传回调用方。
「MultiReader 与 LimitReader 组合读取」这个示例怎么运行?
把它当完整程序编译/解释运行即可——不需要先安装任何东西。
核心语句
if err != nil {
panic(err)
}
代码示例
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
header := strings.NewReader("id=42
")
body := bytes.NewBufferString("name=gadget
price=199
")
// MultiReader:按顺序串接多个 Reader,读完一个再读下一个
combined := io.MultiReader(header, body)
all, err := io.ReadAll(combined)
if err != nil {
panic(err)
}
fmt.Printf("combined %d bytes:
%s", len(all), all)
// LimitReader:最多只读 N 字节,之后表现为 EOF
limited := io.LimitReader(strings.NewReader("0123456789ABCDEF"), 10)
truncated, _ := io.ReadAll(limited)
fmt.Printf("limited: %q (%d bytes)
", truncated, len(truncated))
// 组合使用:拼接后的整体流也能按字节预算截断
capped := io.LimitReader(io.MultiReader(strings.NewReader("aaaa"), strings.NewReader("bbbb")), 6)
head, _ := io.ReadAll(capped)
fmt.Printf("capped: %q
", head)
}