我们在第4章“复合类型的使用”中首先讨论了strings
包。本节将讨论与文件输入和输出相关的strings
包。
str.go
第一部分代码如下:
package mainimport ("fmt""io""os""strings")
str.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
的最后一段代码如下:
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.gor length 4Read t Bytes: 1Read e Bytes: 1Read s Bytes: 1Read t Bytes: 1r length: 18This is an error!Wrote 18 bytes to os.Stderr$ go run str.go 2>/dev/nullr length 4Read t Bytes: 1Read e Bytes: 1Read s Bytes: 1Read t Bytes: 1r length: 18Wrote 18 bytes to os.Stderr