bufio.Scanner
- Go course
- Intermediate
- Lesson 38/80
- 4 min
Learn to read lines with bufio.Scanner.
bufio.Scanner
bufio.Scanner is the easiest way to read a Reader line by line (or word by word):
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
satir := sc.Text()
fmt.Println(len(satir))
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}When Scan returns false reading has ended; Err() says whether the reason was an error (EOF doesn't count as one).
Split functions
A Scanner decides what counts as a "token" with a split function: the default is bufio.ScanLines, and there are also ScanWords, ScanRunes and ScanBytes.
sc := bufio.NewScanner(strings.NewReader("bir iki üç"))
sc.Split(bufio.ScanWords)
n := 0
for sc.Scan() { n++ }
fmt.Println(n) // 3For writing, bufio.NewWriter merges small writes; don't forget to call Flush() at the end.
Practice Count lines
Read the text "elma\narmut\n\nkiraz" line by line with a bufio.Scanner; count the non-empty lines and print the count. Check sc.Err() after the loop.
Starter code
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
sc := bufio.NewScanner(strings.NewReader("elma\narmut\n\nkiraz"))
n := 0
for sc.Scan() {
if sc.Text() != "" {
n++
}
}
if err := sc.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Println(n)
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 By default, what is the longest line a Scanner can read?
- Unlimited
- 1 KB
- 1 MB
- 64 KB; longer lines give bufio.ErrTooLong Correct answer
Explanation: For long lines, grow the buffer with sc.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024).
2 Word by word
sc := bufio.NewScanner(r)
sc.Split(bufio.____)
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
Explanation: ScanWords returns words separated by whitespace one at a time.
3 bufio part
| Term | Meaning |
|---|---|
sc.Scan() |
Move to the next token |
sc.Text() |
Get the token as a string |
sc.Err() |
Read error |
w.Flush() |
Write out the buffer |