跳至主要内容

[pkg] io/reader

在 Go 內建的函式中,有很多的 interfaces 都有實作這個方法,包括 files, network connections, compressors, ciphers 等等。

Reader Interface

type Reader interface {
Read(p []byte) (n int, err error)
}

io.Reader

io.Reader 這個 interface 中有 implement Read 這個方法:

func (T) Read(b []byte) (n int, err error)

當讀到 stream 的最後時,err 會回傳 io.EOF 的錯誤訊息,否則 err 會是 nil

// https://tour.golang.org/methods/21
func main() {
r := strings.NewReader("Hello, Reader!")

b := make([]byte, 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
}
}
}

//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] = ""

Copy

func Copy: func Copy(dst Writer, src Reader) (written int64, err error)