08.11 再看strings包

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

str.go第一部分代码如下:

package main

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

str.go的第二段代码如下:

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

strings.NewReader()函数从字符串创建只读Readerstrings.Reader对象实现了io.Readerio.ReaderAtio.Seekerio.WriterToio.ByteScannerio.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的最后一段代码如下:

    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

Last updated