Golang 中的 bytes 包是其中一個 IO 操作標(biāo)準(zhǔn)庫,實現(xiàn)了對字節(jié)切片([]byte)的操作,提供了類似于 strings 包的功能。本文先講解一下 bytes 包中的結(jié)構(gòu)體 bytes.Reader。
bytes.Reader
bytes.Reader 實現(xiàn)了 io.Reader、io.ReaderAt、io.WriterTo、io.Seeker、io.ByteScanner 和 io.RuneScanner接口,提供了從字節(jié)切片中讀取數(shù)據(jù)的功能。結(jié)構(gòu)體定義和對應(yīng)的方法如下:
type Reader struct {
s []byte
i int64 // current reading index
prevRune int // index of previous rune; or < 0
}
下面是 bytes.Reader 提供的方法:
- func (r *Reader) Len() int,返回字節(jié)切片中未被讀取的字節(jié)數(shù)。
- func (r *Reader) Read(b []byte) (n int, err error),從 bytes.Reader 中讀取數(shù)據(jù)并填充到 b 字節(jié)切片中。
- func (r *Reader) ReadAt(b []byte, off int64) (n int, err error),類似于 Read,但使用偏移量 off 指定從哪里開始讀取。
- func (r *Reader) ReadByte() (byte, error),從字節(jié)切片中讀取一個字節(jié)并返回。
- func (r *Reader) ReadRune() (ch rune, size int, err error),從字節(jié)切片中讀取一個 UTF-8 編碼的字符,并返回該字符的 Unicode 編碼點和字符長度。
- func (r *Reader) Seek(offset int64, whence int) (int64, error),從字節(jié)切片中移動讀取指針,offset 表示偏移量,whence 表示移動的基準(zhǔn)位置。
- func (r *Reader) UnreadByte() error,撤消最后一次讀取操作并將讀取指針向后移動一個字節(jié)。
- func (r *Reader) UnreadRune() error,撤消最后一次讀取操作并將讀取指針向后移動一個 UTF-8 字符。
- func (r *Reader) Size() int64,返回原始字節(jié)切片的長度。
- func (r *Reader) Reset(b []byte),重置 Reader從 b 中讀取數(shù)據(jù)
- func (r *Reader) WriteTo(w io.Writer),寫入數(shù)據(jù)到 w 中直到寫完為止。
使用示例
package main
import (
"bytes"
"fmt"
)
func main() {
data := []byte("路多辛的所思所想")
reader := bytes.NewReader(data)
// 讀取整個字節(jié)數(shù)組
buf := make([]byte, len(data))
_, err := reader.Read(buf)
if err != nil {
fmt.Println("Read failed:", err)
}
fmt.Println("Bytes read:", buf)
// 讀取字節(jié)切片的一部分
part := make([]byte, 3)
_, err = reader.Read(part)
if err != nil {
fmt.Println("Read failed:", err)
}
fmt.Println("Bytes read:", part)
// 查找并讀取字節(jié)切片中的某個字符
offset, err := reader.Seek(6, 0)
if err != nil {
fmt.Println("Seek failed:", err)
}
ch, size, err := reader.ReadRune()
if err != nil {
fmt.Println("ReadRune failed:", err)
}
fmt.Printf("Read %c with size %d at offset %d\n", ch, size, offset)
}
首先定義了一個字節(jié)切片 data,作為參數(shù)傳入 bytes.NewReader 函數(shù)創(chuàng)建一個 reader 對象。然后使用 reader 對象的 Read 方法讀取整個字節(jié)切片和一部分數(shù)據(jù),并使用 Seek 和 ReadRune 方法查找字節(jié)切片中的某個字符并讀取。文章來源:http://www.zghlxwxcb.cn/news/detail-527227.html
小結(jié)
bytes.Reader 可以很方便地處理和讀取字節(jié)切片,可以像讀取文件一樣讀取字節(jié)切片中的數(shù)據(jù),功能非常強大和實用。文章來源地址http://www.zghlxwxcb.cn/news/detail-527227.html
到了這里,關(guān)于Golang 中的 bytes 包詳解(二):bytes.Reader的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!