# 08.11 再看strings包

我们在第4章“复合类型的使用”中首先讨论了`strings`包。本节将讨论与文件输入和输出相关的`strings`包。

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

```go
package main

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

`str.go`的第二段代码如下：

```go
func main() {
    r := strings.NewReader("test")
    fmt.Println("r length", r.Len())
```

`strings.NewReader()`函数从字符串创建只读`Reader`。`strings.Reader`对象实现了`io.Reader`、`io.ReaderAt`、`io.Seeker`、`io.WriterTo`、`io.ByteScanner`和`io.RuneScanner`接口。

`str.go`第三部分代码如下：

```
    b := make([]byte, 1)
    for {
        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)
    }
```

此处，你可以看到如何使用`strings.Reader`作为`io.Reader`接口，从而使用`Read()`函数逐字节读取字符串。

`str.go`的最后一段代码如下：

```go
    s := strings.NewReader("This is an error!\n")
    fmt.Println("r length:", s.Len())
    n, err := s.WriteTo(os.Stderr)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("Wrote %d bytes to os.Stderr\n", n)
}
```

在这段代码中，你可以看到如何在`strings`包的帮助下编写标准错误。

```
$ go run str.go 
r length 4
Read t Bytes: 1
Read e Bytes: 1
Read s Bytes: 1
Read t Bytes: 1
r length: 18
This is an error!
Wrote 18 bytes to os.Stderr
$ go run str.go 2>/dev/null
r length 4
Read t Bytes: 1
Read e Bytes: 1
Read s Bytes: 1
Read t Bytes: 1
r length: 18
Wrote 18 bytes to os.Stderr
```


---

# 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.11.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.
