# 08.12 关于bytes包

\#**关于bytes包**

`byte`包包含处理字节切片的函数，方法与帮助处理字符串的`strings`包方法相同。`Go`源代码文件的名称是`bytes.go`。它分为三部分。

> *这部分内容不包含在`Go`系统编程中，Packet出版，2017*

`byte.go`第一部分代码如下：

```go
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
)
```

`byte.go`第二部分代码如下：

```go
func main() {
	var buffer bytes.Buffer
	buffer.Write([]byte("This is"))
	fmt.Fprintf(&buffer, " a string!\n")
	buffer.WriteTo(os.Stdout)
	buffer.WriteTo(os.Stdout)
```

首先，创建一个新的`bytes.Buffer`变量，通过`buffer.Write()`和`fmt.Fprintf()`写入数据。然后调用`buffer.WriteTo()`两次。

第一次调用`buffer.WriteTo()`将打印`buffer`的内容。然而，第二次调用`buffer.WriteTo()`将不会有任何输出，因为在第一次调用后，`buffer`内容为空。

`bytes.go`最后一部分代码如下：

```go
	buffer.Reset()
	buffer.Write([]byte("Mastering Go!"))
	r := bytes.NewReader([]byte(buffer.String()))
	fmt.Println(buffer.String())
	for {
		b := make([]byte, 3)
		n, err := r.Read(b)
		if err == io.EOF {
			break
		}

		if err != nil {
			fmt.Println(err)
			continue
		}

		fmt.Printf("Read %s Bytes: %d\n", b, n)
	}
}
```

`Reset()`方法重置`buffer`变量，通过`Write()`方法再次写入一些数据。然后你可以通过`bytes.NewReader()`创建新的读对象，再使用`io.Reader`接口方法`Read()`从`buffer`变量读取数据。

执行`bytes.go`会产生如下的输出：

```shell
$ go run byte.go 
This is a string!
Mastering Go!
Read Mas Bytes: 3
Read ter Bytes: 3
Read ing Bytes: 3
Read  Go Bytes: 3
Read ! Bytes: 1
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/08.0/08.12.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
