Go 1.27 reference · Files, HTTP and Logging

Go bufio.Scanner Type

Read input line by line (or word by word) from a file, string or stdin without loading it all into memory.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func NewScanner(r io.Reader) *Scanner

Parameters

ParameterDescription
Scan() / Text() Advance and read the current token.
Split(bufio.ScanWords) Tokens other than lines.
Buffer(buf, max) Allow lines longer than 64 KB.
Err() Check after the loop.

Examples

Example 1
package main

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

func main() {
	input := "GET /\nPOST /orders\nGET /health\n"
	sc := bufio.NewScanner(strings.NewReader(input))
	gets := 0
	for sc.Scan() {
		if strings.HasPrefix(sc.Text(), "GET") {
			gets++
		}
	}
	fmt.Println("GET requests:", gets, "error:", sc.Err())
}

Output

GET requests: 2 error: <nil>

Run this on your computer — see “Get Started” for setup.

Counting words
package main

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

func main() {
	sc := bufio.NewScanner(strings.NewReader("the quick brown fox"))
	sc.Split(bufio.ScanWords)
	n := 0
	for sc.Scan() {
		n++
	}
	fmt.Println(n, "words")
}

Output

4 words

Run this on your computer — see “Get Started” for setup.

Was this page helpful?