一些抽象化的接口
读相关
名称 | 作用 | 备注 |
---|---|---|
Read | 读接口 | 1 |
ReadCloser | 读接口(包含 Close接口) | 2 |
ReadSeeker | 从哪里读到哪里 | 3 |
ReaderAt | 从一定距离开始读 | 4 |
ReaderFrom | 包含 ReadForm方法,读到Eof 或 error停止。返回读到的字节数 | 5 |
写相关
名称 | 作用 | 备注 |
---|---|---|
Writer | 读接口 | 1 |
WriteCloser | 读接口(包含 Close接口) | 2 |
WriteSeeker | 从哪里读到哪里 | 3 |
WriterAt | 从一定距离开始读 | 4 |
WriterTo | 包含 WriterTo 方法,读到Eof 或 error停止。返回写入的字节数 |
几个函数方法
1. Copy (内部实现了 ReaderFrom 和 WriterTo 接口)
func Copy(dst Writer, src Reader) (written int64, err error)
// 将字符串变成 Reader
r := strings.NewReader("some io.Reader stream to be read\n")
if _, err := io.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}
2. CopyBuffer
func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
r1 := strings.NewReader("first reader\n")
r2 := strings.NewReader("second reader\n")
buf := make([]byte, 8)
// buf is used here...
if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
log.Fatal(err)
}
// ... reused here also. No need to allocate an extra buffer.
if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
log.Fatal(err)
}
/* output:
first reader second reader
*/
3. ReadFull
func ReadFull(r Reader, buf []byte) (n int, err error)
r := strings.NewReader("some io.Reader stream to be read\n")
buf := make([]byte, 4)
if _, err := io.ReadFull(r, buf); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
// minimal read size bigger than io.Reader stream
longBuf := make([]byte, 64)
if _, err := io.ReadFull(r, longBuf); err != nil {
fmt.Println("error:", err)
}
/*output:
some
error: unexpected EOF
*/
4. WriteString
func WriteString(w Writer, s string) (n int, err error)
io.WriteString(os.Stdout, "Hello World")
/*output:
Hello World
*/
有疑问加站长微信联系(非本文作者)