這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Go bytes包
bytes包基本方法的使用
package mainimport ("bytes")func writeUInt16(buff []byte, data uint16) {for i := 0; i < 2; i++ {buff[i] = byte(data >> uint(i*8))}}func spilt(r rune) bool {if r == 'c' {return true}return false}func main() {println("hello world")buff1 := make([]byte, 2) // 建立一個切片writeUInt16(buff1, uint16(12))buff2 := make([]byte, 2) // 建立一個切片writeUInt16(buff2, uint16(12))// 比較兩個位元組數組切片res := bytes.Compare(buff1, buff2)println(res)// 字串轉換為位元組數組buff3 := []byte("hello world hello world")seq := []byte("hello")// Count counts the number of non-overlapping instances of sep in sres = bytes.Count(buff3, seq)println(res)// Contains reports whether subslice is within bcontains := bytes.Contains(buff3, seq) //trueprintln(contains)res = bytes.Index(buff3, seq) // 0println(res)res = bytes.LastIndex(buff3, seq)println(res)/**Rune literals are just an integer value (as you've written).They are "mapped" to their unicode codepoint. */a := rune('e')res = bytes.IndexRune(buff3, a) // -1println(res)println("------------")buff5 := []byte("abcabcabcabc")// SplitN 以 sep 為分隔字元,將 s 切分成多個子串,結果中不包含 sep 本身// 如果 sep 為空白,則將 s 切分成 Unicode 字元列表// 如果 s 中沒有 sep,則將整個 s 作為 [][]byte 的第一個元素返回// 參數 n 表示最多切分出幾個子串,超出的部分將不再切分// 如果 n 為 0,則返回 nil,如果 n 小於 0,則不限制切分個數,全部切分arr := bytes.SplitN(buff5, []byte("a"), 3)for _, v := range arr {for _, t := range v {print(t)print(",")}println("|")}// Fields 以連續的空白字元為分隔字元,將 s 切分成多個子串,結果中不包含空白字元本身// 空白字元有:\t, \n, \v, \f, \r, ' ', U+0085 (NEL), U+00A0 (NBSP)// 如果 s 中只包含空白字元,則返回一個空列表println("------------")buff6 := []byte("abc abc abc abc")arr = bytes.Fields(buff6)for _, v := range arr {for _, t := range v {print(t)print(",")}println("|")}// FieldsFunc 以一個或多個連續的滿足 f(rune) 的字元為分隔字元,// 將 s 切分成多個子串,結果中不包含分隔字元本身// 如果 s 中沒有滿足 f(rune) 的字元,則返回一個空列表println("------------")buff7 := []byte("abcabcabcabc")arr = bytes.FieldsFunc(buff7, spilt)for _, v := range arr {for _, t := range v {print(t)print(",")}println("|")}buff8 := []byte("我是中國人")// 將 s 切分為 Unicode 碼點列表data := bytes.Runes(buff8)for _, elem := range data {println(string(elem))}// Title 將 s 中的所有單詞的首字母修改為其 Title 格式buff9 := bytes.Title(buff7)println(string(buff9))// Map 將 s 中滿足 mapping(rune) 的字元替換為 mapping(rune) 的傳回值// 如果 mapping(rune) 返回負數,則相應的字元將被刪除buff10 := bytes.Map(func(r rune) rune {if r == 'c' {return 'a'}return r}, buff7)println(string(buff10))}
bytes包結構體-bytes.Reader
reader.go檔案
// A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker,// io.ByteScanner, and io.RuneScanner interfaces by reading from// a byte slice.// Unlike a Buffer, a Reader is read-only and supports seeking.type Reader struct {s []bytei int64 // current reading indexprevRune int // index of previous rune; or < 0}
Reader實現了以下介面,
io.Readerio.ReaderAt io.WriterTo io.Seekerio.ByteScannerio.RuneScanner
Unlike a Buffer, a Reader is read-only and supports seeking.
Reader結構體所屬的方法,
func NewReader(b []byte) *Readerfunc (r *Reader) Len() int// Read implements the io.Reader interface// Read 將 len(b) 個位元組讀取到 b 中。func (r *Reader) Read(b []byte) (n int, err error)// ReadAt implements the io.ReaderAt interface // 從位移量off開始讀取len(b)個位元組到 b 中func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)func (r *Reader) ReadByte() (byte, error)func (r *Reader) ReadRune() (ch rune, size int, err error)func (r *Reader) Reset(b []byte)// Seek implements the io.Seeker interface.func (r *Reader) Seek(offset int64, whence int) (int64, error)func (r *Reader) Size() int64// UnreadByte implements the io.ByteScanner interfacefunc (r *Reader) UnreadByte() error// UnreadRune implements the io.RuneScanner interfacefunc (r *Reader) UnreadRune() error// WriteTo implements the io.WriteTo interface// WriteTo writes data to w until there's no more data to write or// when an error occurs.func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
方法的使用樣本,
package mainimport ("bytes""fmt""io")func main() {b1 := []byte("Hello World!")reader := bytes.NewReader(b1)// Read 方法buff := make([]byte, 5)count, err := reader.Read(buff)if err != nil {return}fmt.Printf("read count = %d,read data = %s\n", count, string(buff))// ReadAt 方法buff2 := make([]byte, 5)count, err = reader.ReadAt(buff2, 6)if err != nil {return}fmt.Printf("read count = %d,read data = %s\n", count, string(buff2))for {// 依次返回未被讀取的位元組b, err := reader.ReadByte()if err == io.EOF {break}println(string(b))}println("--------")b2 := []byte("hello 世界!")reader2 := bytes.NewReader(b2)for {// 依次返回未被讀取的runer, _, err := reader2.ReadRune()if err == io.EOF {break}println(string(r))}b3 := []byte("string builder")// Reset resets the Reader to be reading from b.reader2.Reset(b3)println(reader2.Len())println("--------")reader3 := bytes.NewReader(b1)// Seek 設定下一次 Read 或 Write 的位移量為 offset,它的解釋取決於 whence:// 0 表示相對於檔案的起始處,1 表示相對於當前的位移,而 2 表示相對於其結尾處。// Seek 返回新的位移量和一個錯誤,如果有的話。abs, err := reader3.Seek(-2, 2)println(abs)b, _ := reader3.ReadByte()println(string(b))}
bytes包結構體-bytes.Buffer
buffer.go檔案,
// A Buffer is a variable-sized buffer of bytes with Read and Write methods.// The zero value for Buffer is an empty buffer ready to use.type Buffer struct {buf []byte // contents are the bytes buf[off : len(buf)]off int // read at &buf[off], write at &buf[len(buf)]runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each call to WriteRunebootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.lastRead readOp // last read operation, so that Unread* can work correctly.}
Buffer結構體所屬的方法,
func NewBuffer(buf []byte) *Bufferfunc NewBufferString(s string) *Bufferfunc (b *Buffer) Bytes() []bytefunc (b *Buffer) Cap() intfunc (b *Buffer) Grow(n int)func (b *Buffer) Len() intfunc (b *Buffer) Next(n int) []bytefunc (b *Buffer) Read(p []byte) (n int, err error)func (b *Buffer) ReadByte() (byte, error)func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)func (b *Buffer) ReadRune() (r rune, size int, err error)func (b *Buffer) ReadString(delim byte) (line string, err error)func (b *Buffer) Reset()func (b *Buffer) String() stringfunc (b *Buffer) Truncate(n int)func (b *Buffer) UnreadByte() errorfunc (b *Buffer) UnreadRune() errorfunc (b *Buffer) Write(p []byte) (n int, err error)func (b *Buffer) WriteByte(c byte) errorfunc (b *Buffer) WriteRune(r rune) (n int, err error)func (b *Buffer) WriteString(s string) (n int, err error)func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
方法的使用樣本,
package mainimport ("bytes""fmt")func main() {b1 := []byte("hello world!")buf := bytes.NewBuffer(b1)fmt.Printf("buff len=%d\n", buf.Len())fmt.Printf("buff cap=%d\n", buf.Cap())buf.Grow(100)fmt.Printf("buff len=%d\n", buf.Len())fmt.Printf("buff cap=%d\n", buf.Cap())b2 := make([]byte, 6)// Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read.// If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.buf.Read(b2)println(string(b2)) //hellob3 := buf.Next(5)println(string(b3)) //worldb4 := buf.Next(3)println(string(b4))buf2 := bytes.NewBuffer(b1)// ReadBytes reads until the first occurrence of delim in the input,// returning a slice containing the data up to and including the delimiter.b5, _ := buf2.ReadBytes(byte(' '))println(len(b5))println(string(b5))b6 := []byte("go programming")buf3 := bytes.NewBuffer(b1)// Write appends the contents of p to the buffer, growing the buffer as// needed.buf3.Write(b6)println(string(buf3.Bytes()))}
=======END=======