If you need to iterate over each line of a string in Go, you can use the
bufio.Scanner type which provides a convenient interface for reading data such
as newline-delimited lines of text from a file or some other source.
The way to create a Scanner from a multiline
string is by using
takes in an io.Reader interface. The way to
io.Reader from a string is by using the
Once you have a Scanner, you can call the
Scan() method to advance to the next
line which can be accessed through the
Scan() returns a
boolean each time it is called. It will return
false if there are no more
for loop above will continue until the
Scan() method returns false. Each
Scan() is invoked, the next line is accessed using
printed to the standard output.
Errors must be handled by checking if
scanner.Err() is not equal to
returns the first non-EOF error that was
encountered by the Scanner.
Thanks for reading, and happy coding!