var buffer1 bytes.Buffer contents := "Simple byte buffer for marshaling data." fmt.Printf("Write contents %q ... ", contents) buffer1.WriteString(contents) fmt.Printf("The length of buffer: %d ", buffer1.Len()) fmt.Printf("The capacity of buffer: %d ", buffer1.Cap()) fmt.Println()
Write contents "Simple byte buffer for marshaling data." ... //打印结果是这样的 The length of buffer: 39 //这里输出了总长度 是可用长度 也就是未读取的长度 The capacity of buffer: 64 //容量长度
1 // 示例2。 2 p1 := make([]byte, 7) 3 n, _ := buffer1.Read(p1) 4 fmt.Printf("%d bytes were read. (call Read) ", n) 5 fmt.Printf("The length of buffer: %d ", buffer1.Len()) 6 fmt.Printf("The capacity of buffer: %d ", buffer1.Cap()) 7 fmt.Println(string(p1))
下面是输出内容 我们从缓冲区读取了7个字节到p1字节切片里 那么buffer1的属性off(计数器)会向后挪移7个字节 长度也会减去7个字节 我们看下输出结果
7 bytes were read. (call Read)
The length of buffer: 32
The capacity of buffer: 64
再看下截取是示例:
buffer1.Truncate(6) //截取6个字节长度 从计数器为起始位置