這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
bytes.buffer是一個緩衝byte類型的緩衝器存放著都是byte
Buffer 是 bytes 包中的一個 type Buffer struct{…}
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.
(是一個變長的 buffer,具有 Read 和Write 方法。 Buffer 的 零值 是一個 空的 buffer,但是可以使用)
Buffer 就像一個集裝箱容器,可以存東西,取東西(存取資料)
建立 一個 Buffer (其實底層就是一個 []byte, 位元組切片)
向其中寫入資料 (Write mtheods)
從其中讀取資料 (Write methods)
建立 Buffer緩衝器
var b bytes.Buffer //直接定義一個 Buffer 變數,而不用初始化
b.Writer([]byte(“Hello “)) // 可以直接使用
b1 := new(bytes.Buffer) //直接使用 new 初始化,可以直接使用
// 其它兩種定義方式
func NewBuffer(buf []byte) *Buffer
func NewBufferString(s string) *Buffer
NewBuffer
// NewBuffer creates and initializes a new Buffer using buf as its initial
// contents. It is intended to prepare a Buffer to read existing data. It
// can also be used to size the internal buffer for writing. To do that,
// buf should have the desired capacity but a length of zero.
//
// In most cases, new(Buffer) (or just declaring a Buffer variable) is
// sufficient to initialize a Buffer.
func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
NewBuffer使用buf作為參數初始化Buffer,
Buffer既可以被讀也可以被寫
如果是讀Buffer,buf需填充一定的資料
如果是寫,buf需有一定的容量(capacity),當然也可以通過new(Buffer)來初始化Buffer。另外一個方法NewBufferString用一個string來初始化可讀Buffer,並用string的內容填充Buffer.
func IntToBytes(n int) []byte {
x := int32(n)
//建立一個內容是[]byte的slice的緩衝器
//與bytes.NewBufferString(“”)等效
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
NewBufferString
方法NewBufferString用一個string來初始化可讀Buffer,並用string的內容填充Buffer.
用法和NewBuffer沒有太大區別
// NewBufferString creates and initializes a new Buffer using string s as its
// initial contents. It is intended to prepare a buffer to read an existing
// string.
//
// In most cases, new(Buffer) (or just declaring a Buffer variable) is
// sufficient to initialize a Buffer.
func NewBufferString(s string) *Buffer {
return &Buffer{buf: []byte(s)}
}
func TestBufferString(){
buf1:=bytes.NewBufferString(“swift”)
buf2:=bytes.NewBuffer([]byte(“swift”))
buf3:=bytes.NewBuffer([]byte{’s’,’w’,’i’,’f’,’t’})
fmt.Println(“===========以下buf1,buf2,buf3等效=========”)
fmt.Println(“buf1:”, buf1)
fmt.Println(“buf2:”, buf2)
fmt.Println(“buf3:”, buf3)
fmt.Println(“===========以下建立空的緩衝器等效=========”)
buf4:=bytes.NewBufferString(“”)
buf5:=bytes.NewBuffer([]byte{})
fmt.Println(“buf4:”, buf4)
fmt.Println(“buf5:”, buf5)
}
輸出:
===========以下buf1,buf2,buf3等效=========
buf1: swift
buf2: swift
buf3: swift
===========以下建立空的緩衝器等效=========
buf4:
buf5:
向 Buffer 中寫入資料
Write
把位元組切片 p 寫入到buffer中去。
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(p))
return copy(b.buf[m:], p), nil
}
fmt.Println(“===========以下通過Write把swift寫入Learning緩衝器尾部=========”)
newBytes := []byte(“swift”)
//建立一個內容Learning的緩衝器
buf := bytes.NewBuffer([]byte(“Learning”))
//列印為Learning
fmt.Println(buf.String())
//將newBytes這個slice寫到buf的尾部
buf.Write(newBytes)
fmt.Println(buf.String())
列印:
===========以下通過Write把swift寫入Learning緩衝器尾部=========
Learning
Learningswift
WriteString
使用WriteString方法,將一個字串放到緩衝器的尾部
// WriteString appends the contents of s to the buffer, growing the buffer as
// needed. The return value n is the length of s; err is always nil. If the
// buffer becomes too large, WriteString will panic with ErrTooLarge.
func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(s))
return copy(b.buf[m:], s), nil
}
fmt.Println(“===========以下通過WriteString把swift寫入Learning緩衝器尾部=========”)
newString := “swift”
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteString(newString)
fmt.Println(buf.String())
列印:
===========以下通過Write把swift寫入Learning緩衝器尾部=========
Learning
Learningswift
WriteByte
將一個byte類型的資料放到緩衝器的尾部
// WriteByte appends the byte c to the buffer, growing the buffer as needed.
// The returned error is always nil, but is included to match bufio.Writer’s
// WriteByte. If the buffer becomes too large, WriteByte will panic with
// ErrTooLarge.
func (b *Buffer) WriteByte(c byte) error {
b.lastRead = opInvalid
m := b.grow(1)
b.buf[m] = c
return nil
}
fmt.Println(“===========以下通過WriteByte把!寫入Learning緩衝器尾部=========”)
var newByte byte = ‘!’
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteByte(newByte)
fmt.Println(buf.String())
列印:
===========以下通過WriteByte把swift寫入Learning緩衝器尾部=========
Learning
Learning!
WriteRune
將一個rune類型的資料放到緩衝器的尾部
// WriteRune appends the UTF-8 encoding of Unicode code point r to the
// buffer, returning its length and an error, which is always nil but is
// included to match bufio.Writer’s WriteRune. The buffer is grown as needed;
// if it becomes too large, WriteRune will panic with ErrTooLarge.
func (b *Buffer) WriteRune(r rune) (n int, err error) {
if r < utf8.RuneSelf {
b.WriteByte(byte(r))
return 1, nil
}
n = utf8.EncodeRune(b.runeBytes[0:], r)
b.Write(b.runeBytes[0:n])
return n, nil
}
fmt.Println(“===========以下通過WriteRune把\”好\”寫入Learning緩衝器尾部=========”)
var newRune = ‘好’
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteRune(newRune)
fmt.Println(buf.String())
列印:
===========以下通過WriteRune把”好”寫入Learning緩衝器尾部=========
Learning
Learning好
完整樣本
package main
import (
“bytes”
“encoding/binary”
“fmt”
)
func main() {
//newBuffer 整形轉換成位元組
var n int = 10000
intToBytes := IntToBytes(n)
fmt.Println(“==========int to bytes========”)
fmt.Println(intToBytes)
//NewBufferString
TestBufferString()
//write
BufferWrite()
//WriteString
BufferWriteString()
//WriteByte
BufferWriteByte()
//WriteRune
BufferWriteRune()
}
func IntToBytes(n int) []byte {
x := int32(n)
//建立一個內容是[]byte的slice的緩衝器
//與bytes.NewBufferString(“”)等效
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
func TestBufferString(){
buf1:=bytes.NewBufferString(“swift”)
buf2:=bytes.NewBuffer([]byte(“swift”))
buf3:=bytes.NewBuffer([]byte{’s’,’w’,’i’,’f’,’t’})
fmt.Println(“===========以下buf1,buf2,buf3等效=========”)
fmt.Println(“buf1:”, buf1)
fmt.Println(“buf2:”, buf2)
fmt.Println(“buf3:”, buf3)
fmt.Println(“===========以下建立空的緩衝器等效=========”)
buf4:=bytes.NewBufferString(“”)
buf5:=bytes.NewBuffer([]byte{})
fmt.Println(“buf4:”, buf4)
fmt.Println(“buf5:”, buf5)
}
func BufferWrite(){
fmt.Println(“===========以下通過Write把swift寫入Learning緩衝器尾部=========”)
newBytes := []byte(“swift”)
//建立一個內容Learning的緩衝器
buf := bytes.NewBuffer([]byte(“Learning”))
//列印為Learning
fmt.Println(buf.String())
//將newBytes這個slice寫到buf的尾部
buf.Write(newBytes)
fmt.Println(buf.String())
}
func BufferWriteString(){
fmt.Println(“===========以下通過Write把swift寫入Learning緩衝器尾部=========”)
newString := “swift”
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteString(newString)
fmt.Println(buf.String())
}
func BufferWriteByte(){
fmt.Println(“===========以下通過WriteByte把swift寫入Learning緩衝器尾部=========”)
var newByte byte = ‘!’
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteByte(newByte)
fmt.Println(buf.String())
}
func BufferWriteRune(){
fmt.Println(“===========以下通過WriteRune把\”好\”寫入Learning緩衝器尾部=========”)
var newRune = ‘好’
//建立一個string內容Learning的緩衝器
buf := bytes.NewBufferString(“Learning”)
//列印為Learning
fmt.Println(buf.String())
//將newString這個string寫到buf的尾部
buf.WriteRune(newRune)
fmt.Println(buf.String())
}
**
向 Buffer 中讀取資料
**
Read
給Read方法一個容器p,讀完後,p就滿了,緩衝器相應的減少了,返回的n為成功讀的數量
// 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.
func (b *Buffer) Read(p []byte) (n int, err error) {}
func Read(){
bufs := bytes.NewBufferString(“Learning swift.”)
fmt.Println(bufs.String())
//聲明一個空的slice,容量為8l := make([]byte, 8)//把bufs的內容讀入到l內,因為l容量為8,所以唯讀了8個過來bufs.Read(l)fmt.Println("::bufs緩衝器內容::")fmt.Println(bufs.String())//空的l被寫入了8個字元,所以為 Learningfmt.Println("::l的slice內容::")fmt.Println(string(l))//把bufs的內容讀入到l內,原來的l的內容被覆蓋了bufs.Read(l)fmt.Println("::bufs緩衝器被第二次讀取後剩餘的內容::")fmt.Println(bufs.String())fmt.Println("::l的slice內容被覆蓋,由於bufs只有7個了,因此最後一個g被留下來了::")fmt.Println(string(l))
}
列印:
=======Read=======
Learning swift.
::bufs緩衝器內容::
swift.
::l的slice內容::
Learning
::bufs緩衝器被第二次讀取後剩餘的內容::
::l的slice內容被覆蓋::
swift.g
ReadByte
返回緩衝器頭部的第一個byte,緩衝器頭部第一個byte被拿掉
// ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error io.EOF.
func (b *Buffer) ReadByte() (c byte, err error) {}
func ReadByte(){
bufs := bytes.NewBufferString(“Learning swift.”)
fmt.Println(bufs.String())
//讀取第一個byte,賦值給b
b, _ := bufs.ReadByte()
fmt.Println(bufs.String())
fmt.Println(string(b))
}
列印:
=======ReadByte===
Learning swift.
earning swift.
L
ReadRune
ReadRune和ReadByte很像
返回緩衝器頭部的第一個rune,緩衝器頭部第一個rune被拿掉
// ReadRune reads and returns the next UTF-8-encoded
// Unicode code point from the buffer.
// If no bytes are available, the error returned is io.EOF.
// If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() (r rune, size int, err error) {}
func ReadRune(){
bufs := bytes.NewBufferString(“學swift.”)
fmt.Println(bufs.String())
//讀取第一個rune,賦值給rr,z,_ := bufs.ReadRune()//列印中文"學",緩衝器頭部第一個被拿走fmt.Println(bufs.String())//列印"學","學"作為utf8儲存佔3個bytefmt.Println("r=",string(r),",z=",z)
}
ReadBytes
ReadBytes需要一個byte作為分隔字元,讀的時候從緩衝器裡找第一個出現的分隔字元(delim),找到後,把從緩衝器頭部開始到分隔字元之間的所有byte進行返回,作為byte類型的slice,返回後,緩衝器也會空掉一部分
// ReadBytes reads until the first occurrence of delim in the input,
// returning a slice containing the data up to and including the delimiter.
// If ReadBytes encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in
// delim.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {}
func ReadBytes(){
bufs := bytes.NewBufferString(“現在開始 Learning swift.”)
fmt.Println(bufs.String())
var delim byte = 'L'line, _ := bufs.ReadBytes(delim)fmt.Println(bufs.String())fmt.Println(string(line))
}
列印:
=======ReadBytes==
現在開始 Learning swift.
earning swift.
現在開始 L
ReadString
ReadString需要一個byte作為分隔字元,讀的時候從緩衝器裡找第一個出現的分隔字元(delim),找到後,把從緩衝器頭部開始到分隔字元之間的所有byte進行返回,作為字串,返回後,緩衝器也會空掉一部分
和ReadBytes類似
// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end
// in delim.
func (b *Buffer) ReadString(delim byte) (line string, err error) {}
ReadFrom
從一個實現io.Reader介面的r,把r裡的內容讀到緩衝器裡,n返回讀的數量
// ReadFrom reads data from r until EOF and appends it to the buffer, growing
// the buffer as needed. The return value n is the number of bytes read. Any
// error except io.EOF encountered during the read is also returned. If the
// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {}
func ReadFrom(){
//test.txt 內容是 “未來”
file, _ := os.Open(“learngo/bytes/text.txt”)
buf := bytes.NewBufferString(“Learning swift.”)
buf.ReadFrom(file) //將text.txt內容追加到緩衝器的尾部
fmt.Println(buf.String())
}
列印:
=======ReadFrom===
Learning swift.未來
Reset
將資料清空,沒有資料可讀
// Reset resets the buffer so it has no content.
// b.Reset() is the same as b.Truncate(0).
func (b *Buffer) Reset() { b.Truncate(0) }
func Reset(){
bufs := bytes.NewBufferString(“現在開始 Learning swift.”)
fmt.Println(bufs.String())
bufs.Reset()fmt.Println("::已經清空了bufs的緩衝內容::")fmt.Println(bufs.String())
}
列印:
=======Reset======
現在開始 Learning swift.
::已經清空了bufs的緩衝內容::
string
將未讀取的資料返回成 string
// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns “”.
func (b *Buffer) String() string {}