0PricingLogin
Go Academy · Lesson

Scanners

Read line by line.

What is bufio.Scanner

bufio.Scanner is the easiest way to read input token by token, most commonly line by line.

It hides buffering and delimiter handling, and strips the trailing newline for you.

Scanning Lines

Create a scanner, then loop with Scan() which returns false at end. Read the current token with Text().

package main

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

func main() {
	s := bufio.NewScanner(strings.NewReader("one\ntwo\nthree"))
	for s.Scan() {
		fmt.Println("line:", s.Text())
	}
}

All lessons in this course

  1. Buffered Readers
  2. Scanners
  3. Buffered Writers
  4. Streaming Large Files
← Back to Go Academy