bufio.Reader buffers input so programs perform fewer underlying read operations and system calls. It also exposes familiar reading methods through the io.Reader interface. section 3.5 section 5.1.2
Use bufio.Reader when:
- Reading repeated input from a source such as standard input. section 5.1.2
- Reading complete input lines with ReadLine, excluding the end-of-line bytes. section 5.1.2
- Injecting input into reusable code by accepting an io.Reader and constructing the buffer with bufio.NewReader. section 5.1.2
Reading guesses in a terminal word game
A Game stores a pointer to bufio.Reader. New accepts an io.Reader and wraps it with bufio.NewReader; ask repeatedly calls ReadLine, converts the bytes to []rune, rejects guesses with the wrong character count, and retries. main passes os.Stdin. Tests pass strings.NewReader with English, Arabic, and Japanese guesses. section 5.1.2
Listing 5.6 game.go: Using New with the reader as parameter
// New returns a Game variable, which can be used to Play!
func New(playerInput io.Reader) *Game {
g := &Game{
reader: bufio.NewReader(playerInput),
}
return g
}
Shows how New receives an io.Reader and creates a bufio.Reader without coupling the game to a particular input source. section 5.1.2
