Adding Command-Line Flags

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing the Basic Word Counter | TOC | Compiling Your Tool for Dif ferent Platforms 👉

Good command-line tools provide flexibility through options. The current version of the word counter tool counts words. Let’s add the ability to count lines as well by giving the user the option to decide when to switch this behavior through command-line flags.

Go provides the flag package, which you can use to create and manage command-line flags. You’ll learn about it in more detail in Handling Multiple Command-Line Options. For now, open the main.go file and add this package to your imports section:

​ ​import​ (
​ ​"bufio"​
» ​"flag"​
​ ​"fmt"​
​ ​"io"​
​ ​"os"​
​ )

Next, update the main function by adding the definition for the new command-line flag:

​ ​func​ main() {
​ ​// Defining a boolean flag -l to count iines instead of words​
​ lines := flag.Bool(​"l"​, false, ​"Count lines"​)
​ ​// Parsing the flags provided by the user​
​ flag.Parse()

This defines a new -l option that we’ll use to indicate whether to count lines. The default value is false, which means that the normal behavior is to count words.

Complete the main function by updating the call to the function count, passing the value of the flag:

​   ​// Calling the count…

--

--

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.