一、俩个数据类型
-
io.Reader和io.Writer
-
type Reader interface { Reade(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) }
-
以上俩种数据类型都被定义为接口,意味着不能直接被实例化。
-
type abcReader struct { } func (r *abcReader) Read(p []byte) (int, error) { return 1, nil } type abcWriter struct { } func (r *abcWriter) Write(p []byte) (int, error) { return 1, nil }
-
参照上述示例,可以自定义包装了stdin,stdout 的Reader和Writer
-
package main import ( "fmt" "log" "os" ) type abcReader struct { } func (r *abcReader) Read(p []byte) (int, error) { return os.Stdin.Read(p) } type abcWriter struct { } func (r *abcWriter) Write(p []byte) (int, error) { return os.Stdout.Write(p) } func main() { var reader abcReader var writer abcWriter fmt.Printf("please input a string.\n") //创建缓冲区,保存输入输出 input := make([]byte, 4096) //使用reader 读取输入 n, err := reader.Read(input) if err != nil { log.Fatalln("Unable to read data") } fmt.Printf("read %d bytes from stdin\n", n) //使用writer写入输出 n2, err := writer.Write(input[:n]) if err != nil { log.Fatalln("Unable to write data") } fmt.Printf("write %d bytes to stout\n", n2) /** please input a string. i love you read 12 bytes from stdin i love you write 12 bytes to stout */ }
-
将数据从Reader复制到writer是一种常见的模式,促使go 提供了一个Copy函数,func Copy(dst io.Writer,src io.Reader) (written int64,error)
-
package main import ( "fmt" "io" "log" "os" ) type abcReader struct { } func (r *abcReader) Read(p []byte) (int, error) { return os.Stdin.Read(p) } type abcWriter struct { } func (r *abcWriter) Write(p []byte) (int, error) { return os.Stdout.Write(p) } func main() { var reader abcReader var writer abcWriter fmt.Printf("please input a string.\n") if _, err := io.Copy(&writer, &reader); err != nil { log.Fatal("Unable to read/write data") } /** please input a string. i love you i love you */ }