Chapter 7. General Input/Output Recipes

7.0 Introduction

Input and output (more popularly known as I/O) are how a computer communicates with the external world. Typical input into a computer refers to the keystrokes from a keyboard or clicks from or movement of a mouse. It can also refer to other external input sources like a camera or a microphone, gaming joystick, and so on. Output often refers to whatever is shown on the screen (or on the terminal) or printed out on a printer. I/O can also refer to network connections and to files. I/O is a key part of developing software and most programming languages, including Go, have standard libraries that can read from input and write to output.

This chapter explores some common Go recipes for managing I/O. We’ll warm up with some basic I/O recipes, then talk about files in general. In the next few chapters, we’ll move on to CSV, followed by JSON and binary files.

The io package is the base package for input and output in Go and contains interfaces for I/O and a few convenient functions. The main and the most commonly used interfaces are Reader and Writer, but there are several variants of these, like ReadWriter, TeeReader, WriterTo, and many more.

Generally, these interfaces are nothing more than a descriptor for functions. For example, a struct that is a Reader has a Read function. A struct that is a WriterTo has a WriteTo function. Some interfaces combine two or more interfaces. For example, the ReadWriter combines the Reader and ...

Get Go Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.