ProgramGuru

The bufio Package

Start with The bufio Package

The bufio package buffers I/O and supports convenient line-oriented reading with scanners.

What you’ll learn

  • Explain the main purpose of the bufio package.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

bufio.NewScanner reads text in tokens, lines by default. Call Scan() in a loop, read Text(), and check Err() afterwards. For larger input or more control, buffered readers and writers expose additional methods.

Scanner has a configurable token-size limit; it is not appropriate for unlimited-length lines without configuration. This example reads from a string reader so it requires no interactive input or external files.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for bufioThe condition controls repeated execution; the update returns to the condition until the loop stops.NewScannerScan succeeds?Process TextNext Scanrepeat while trueWhen the condition becomes false → Check Err after loop
Trace control flow in the order shown, then compare it with the program.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	input := strings.NewReader("red\nblue\ngreen\n")
	scan := bufio.NewScanner(input)
	count := 0
	for scan.Scan() {
		count++
		fmt.Println(count, scan.Text())
	}
	if err := scan.Err(); err != nil {
		fmt.Println("Read error:", err)
	}
}

Output

1 red
2 blue
3 green

Trace what the program does

The scanner reads three lines in order. Each Scan call updates the current token; after scanning completes, Err is checked for a read failure.

Avoid common mistakes

  • Always check Scanner.Err after the loop.
  • Long tokens may exceed Scanner’s default maximum token size.

Try it yourself

Change the sample input to four lines and count how many are nonempty.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

When should Scanner.Err be checked?
Choose one answer. You can try again.

Answer and explanation

After a Scan loop ends

Correct. The scanner reads three lines in order.

What you should remember

You have practiced The bufio Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Working with Directories →