This is a creation in Article, where the information may have evolved or changed.
The IO package for the Go language specifies IO. Reader interface. The Go Language standard library contains many implementations of this interface, including files, network connections, compression, encryption, and so on.
Io. The Reader interface has a Read method:
func (T) Read(b []byte) (n int, err error)
In the program, we use a loop to read the data stream until the error returns IO. Eof.
We build a strings that reads in 8 bytes at a time. Example of a program for the output of Reader.
package mainimport( "fmt" "strings" "io")func main() { r := strings.NewReader("Hello, Reader!") b := make([]byte, 8) // 8 这里控制每次读取的字节数 for{ n, err := r.Read(b) fmt.Printf("n = %v err = %v b = %v\n", n, err, b) fmt.Printf("b[:n] = %q\n", b[:n]) if err == io.EOF{ break } }}
Run results
n = 8 err = <nil> b = [72 101 108 108 111 44 32 82]b[:n] = "Hello, R"n = 6 err = <nil> b = [101 97 100 101 114 33 32 82]b[:n] = "eader!"n = 0 err = EOF b = [101 97 100 101 114 33 32 82]b[:n] = ""
Let me show you one more example. This example implements a Reader type, which constantly generates a stream of ASCII characters ' a '.
Package Mainimport ("FMT" "IO" "OS") type myreader struct{}func Validate (R io). Reader) {b: = make ([]byte, 1024x768, 2048) I, O: = 0, 0 for; i < 1<<20 && O < 1<<20; i++ {//Test 1MB N, err: = R.read (b) for I, V: = Range B[:n] {if v! = ' A ' {fmt. fprintf (OS. Stderr, "Got byte%x at offset%v, want ' A ' \ n", V, O+i) return}} O + = n i F Err! = Nil {fmt. fprintf (OS. Stderr, "read error:%v\n", err) return}} if o = = 0 {fmt. fprintf (OS. Stderr, "read zero bytes after%d read calls\n", i) return} FMT. Println ("ok!")} Implements a Reader type, which constantly generates a stream of ASCII characters ' a '. Todo:add a read ([]byte) (int, error) method to Myreader.func (Mr Myreader) read (b []byte) (n int, err error) {i: = 0 for; i < Len (b); i++ {b[i] = ' A '} return I, Nil}func main () {Validate (myreader{})}
The Func Validate (R io) in the
code. Reader) can be downloaded from GitHub.
Golang.org/x/tour/reader