Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.
io.Reader
The io
package specifies the io.Reader
interface, which represents the read end of a stream of data.
Read
populates the given byte slice
with data
and returns the number of bytes
populated and an error
value.
It returns an io.EOF error
when the stream ends.
package main import ( "fmt" "io" "strings" ) func main() { // strings io.Reader example r := strings.NewReader("Hello, Reader!") // 8 byte at a time b := make([]byte, 8) for { // reads from byte arr r 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 } } }
io.Writer
io.Writer
is an interface that wraps the basic Write
method.
Writer
is a byte array
.type Writer interface { Write(p []byte) (n int, err error) }
See os
section on writing to byte array
.