How to iterate over multiline strings in Go
In this article, we will discuss the best approach to iterating over each line of a newline delimited string (such as the contents of text files) in Go
If you need to iterate over each line of a string in Go (such as each line of a
file), you can use the bufio.Scanner
type which provides a convenient
interface for reading data such as lines of text from any source. The way to
create a Scanner from a multiline string is
by using the bufio.NewScanner()
method which takes in any type that implements
the io.Reader interface as its only
argument.
If you want to read a file line by line, you can call os.Open()
on the
file name and pass the resulting os.File
to NewScanner()
since it implements
io.Reader
. You can also cause an ordinary string to implement the io.Reader
interface by calling the strings.NewReader()
method on it.
Once you have a Scanner, you can call the Scan()
method to advance to the next
line which can be accessed through the Text()
method. Scan()
returns a
boolean each time it is called. It will return false
if there are no more
lines.
Here’s an example that reads an HTML file line by line in Go. Here’s the file in question:
And here’s the code to iterate over each line in the file:
The for
loop above will continue until the Scan()
method returns false. Each
time Scan()
is invoked, the next line is accessed using scanner.Text()
and
printed to the standard output. Errors must be handled by checking if
scanner.Err()
is not equal to nil
. It returns the first non-EOF error that was encountered by the Scanner.
Thanks for reading, and happy coding!