typestar

Reading lines in Go

bufio.Scanner walks a reader line by line, and its error needs checking.

func countLines(input string) (int, int, error) {
    scanner := bufio.NewScanner(strings.NewReader(input))
    scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)

    lines, words := 0, 0
    for scanner.Scan() {
        line := strings.TrimSpace(scanner.Text())
        if line == "" {
            continue
        }
        lines++
        words += len(strings.Fields(line))
    }
    if err := scanner.Err(); err != nil {
        return 0, 0, fmt.Errorf("scan: %w", err)
    }
    return lines, words, nil
}

How it works

  1. Scan returns false at the end or on an error.
  2. Err afterwards distinguishes the two.
  3. Buffer raises the limit for very long lines.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
420
Tokens
129
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 1 of 3 in Files & IO, step 6 of 26 in Standard library & project layout.

← Previous Next →

Reading lines in other languages