Difference Between Golang bufio Reader vs Scanner | NewReader VS NewScanner
Golang default package bufio implements buffered I/O which wraps io.Reader or io.Writer. It also comes with a Scanner and it often get confused with bufio reader due to their similary. In this post we would like to see some differences between scanner vs reader with examples
Scanner vs Reader
- A bufio.Scanner can read from any stream of bytes, as long as it implements the io.Reader
- Scanner helps to process stream of data by splitting it into tokens
- By default it has a 64k line limit.
- Scanner doesn't return the newline byte
- NewReader returns a new Reader whose buffer has the default size (bufio's default buffer size is 4K)
- The text returned from ReadLine does not include the line end ("\r\n" or "\n").
- The reader has the advantage of being an io.Reader
Explanations For Examples
- Example 1: we can see that by default ReadLine is limited to 4K where Scan can read up to 64KB in one line
- Example 2: For many simple cases, we can use both solution interchangeably
I am beginner and tried to explain as I understood. Please let me know if you have different opinion, explanations or examples to simplify this further.