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.
An example of how flag
is used with command-line arguments is shown below.
flag.Int("n", def_val, description)
"n"
: the variable to be parsed.
def_val
: the default value of the variable.
description
: the description of the flag.
package mainimport ("flag""fmt""os")// Define the flagvar help = flag.Bool("help", false, "Show help")var boolFlag = falsevar stringFlag = "Hello There!"var intFlag intfunc main() {// Bind the flagflag.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 flagflag.Parse()// Usage Demoif *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.