Chapter 10. Data IO in Go

Previous chapters of this book focused mainly on fundamentals. In this and future chapters, readers are introduced to some of the powerful APIs provided by Go's standard library. This chapter discusses in detail how to input, process, transform, and output data using APIs from the standard library and their respective packages with the following topics:

  • IO with readers and writers
  • The io.Reader interface
  • The io.Writer interface
  • Working with the io package
  • Working with files
  • Formatted IO with fmt
  • Buffered IO
  • In-memory IO
  • Encoding and decoding data

IO with readers and writers

Similar to other languages, such as Java, Go models data input and output as a stream that flows from sources to targets. Data resources, such as files, networked connections, or even some in-memory objects, can be modeled as streams of bytes from which data can be read or written to, as illustrated in the following figure:

IO with readers and writers

The stream of data is represented as a slice of bytes ([]byte) that can be accessed for reading or writing. As we will explore in this chapter, the io package makes available the io.Reader interface to implement code that reads and transfers data from a source into a stream of bytes. Conversely, the io.Writer interface lets implementers create code that reads data from a provided stream of bytes and writes it as output to a target resource. Both interfaces are used extensively in Go as a standard idiom to express IO operations. This makes it possible to interchange readers and writers of different implementations and contexts with predictable results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.113