-
Book Overview & Buying
-
Table Of Contents
Practical Systems Programming in Go
By :
The classic Unix wc(1) utility is a simple yet powerful tool that counts the number of lines, words, and characters in a text file. Recreating this functionality in Go provides an excellent exercise in file processing and text scanning, as it combines reading from files with efficient counting techniques. Rather than treating each count separately, a single pass through the file can update all three metrics at once, demonstrating how careful design can save time and resources. Creating three separate functions for counting lines, words, and characters independently would require opening and reading the same file three times, wasting I/O operations and CPU cycles.
The count() function serves as the core statistical analysis engine of the word count utility, accepting any io.Reader interface as input. This allows it to work seamlessly with files, standard input, network streams, or any other readable data source in Go:
func count(r io.Reader) (lines, words, bytes, runes...