Search⌘ K
AI Features

Handling Multiple Command-Line Options

Explore how to handle multiple command-line options in Go by using the flag package. Learn to define and parse flags of various types, update program flow based on flag values, and enhance CLI tools for better user interaction and functionality.

As we’ve seen while implementing the initial version of our command-line interface, using the os.Args variable isn’t a flexible way of handling command-line arguments. Let’s improve the tool by using the flag package to parse and handle multiple command-line options.

Command-line flags

The flag package enables us to define command-line flags of specific types such as int or string, so we don’t need to convert them manually. This version of the tool will accept three command-line arguments:

  • -list: A boolean flag. When used, the tool will list all to-do items.
  • -task: A string flag. When used, the tool will include the string argument as a new to-do item in the list.
  • -complete: An integer flag. When used, the tool will mark the item number as completed.


...

Example code

Not ...