> For the complete documentation index, see [llms.txt](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/08.0/08.11.md).

# 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
```
