Building the Basic Word Counter

Powerful Command-Line Applications in Go — by Ricardo Gerardi (11 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 1 Your First Command-Line Program in Go | TOC | Testing the Basic Word Counter 👉

Let’s create a tool that counts the number of words or lines provided as input using the standard input (STDIN) connection. By default, this tool will count the number of words, unless it receives the -l flag, in which case it’ll count the number of lines instead.

We’ll start by creating the basic implementation. This version reads data from STDIN and displays the number of words. We’ll eventually add more features, but this initial version will let you get comfortable with the code for a Go-based command-line application.

Before you dive into writing code for the word counter, let’s set up a project directory. In your home directory, create the subdirectory pragprog.com/rggo/firstProgram/wc and switch to it:

​ ​$ ​​mkdir​​ ​​-p​​ ​​$HOME/pragprog.com/rggo/firstProgram/wc​
​ ​$ ​​cd​​ ​​$HOME/pragprog.com/rggo/firstProgram/wc​

Go programs are composed of packages. A package consists of one or more Go source code files with code that can be combined into executable programs or libraries.

Starting with Go 1.11, you can combine one or more packages into Go modules. Modules are a new Go standard for grouping related packages into a single unit that can be versioned together. Modules enable…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.