Line scanning in Go

Today, I needed to keep track of the linenumber while scanning table driven tests. The standard Go bufio.Scanner does not provide such information. Fortunately, in Go you can create your own by embedding the standard type and overriding the right function. That’s it.

import (
	"bufio"
	"io"
)

type linescanner struct {
	*bufio.Scanner
	line int
}

func newScanner(reader io.Reader) *linescanner {
	return &linescanner{bufio.NewScanner(reader), 0}
}

func (l *linescanner) Scan() bool {
	ok := l.Scanner.Scan()
	if ok {
		l.line++
	}
	return ok
}
comments powered by Disqus