
上QQ阅读APP看书,第一时间看更新
Using the common I/O interfaces
Go provides a number of I/O interfaces used throughout the standard library. It is a best practice to make use of these interfaces wherever possible rather than passing structs or other types directly. Two powerful interfaces we explore in this recipe are the io.Reader and io.Writer interfaces. These interfaces are used throughout the standard library and understanding how to use them will make you a better Go developer.
The Reader and Writer interfaces look like this:
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
Go also makes it easy to combine interfaces. For example, take a look at the following code:
type Seeker interface {
Seek(offset int64, whence int) (int64, error)
}
type ReadSeeker interface {
Reader
Seeker
}
The recipe will also explore an io function called Pipe():
func Pipe() (*PipeReader, *PipeWriter)
The remainder of this book will make use of these interfaces.