How to parse command-line flags in Go

Golang has a built-in package called flag that enables one to parse command-line flags. The flag package allows you to define String, Bool, or Int flags.

To be able to access the parameters passed as arguments to the command line execution of your program, three steps need to be completed.

  1. Define the flag.
  2. Bind the flag.
  3. Parse the flag.

Syntax

An example of how flag is used with command-line arguments is shown below.

flag.Int("n", def_val, description)

Parameters

  • "n": the variable to be parsed.

  • def_val: the default value of the variable.

  • description: the description of the flag.

Code

package main
import (
"flag"
"fmt"
"os"
)
// Define the flag
var help = flag.Bool("help", false, "Show help")
var boolFlag = false
var stringFlag = "Hello There!"
var intFlag int
func main() {
// Bind the flag
flag.BoolVar(&boolFlag, "boolFlag", false, "A boolean flag")
flag.StringVar(&stringFlag, "stringFlag", "Hello There!", "A string flag")
flag.IntVar(&intFlag, "intFlag", 4, "An integer flag")
// Parse the flag
flag.Parse()
// Usage Demo
if *help {
flag.Usage()
os.Exit(0)
}
fmt.Println("Boolean Flag is ", boolFlag)
fmt.Println("String Flag is ", stringFlag)
fmt.Println("Int Flag is ", intFlag)
}

To run the code in the terminal, the following command is added.

./main -boolFlag=true -stringFlag hi

Use -h or --help flags to get automatically generated help text for the command-line program.

In case you provide a flag that wasn’t specified to the flag package, the program will print an error message and show the help text again.

Attributions:
  1. undefined by undefined