Go flag

The flag package is used for parsing command-line parameters, making it much simpler to develop command-line tools than relying on the rudimentary os.Args.

Types of Command-line Parameters

Flag TypesValid Values
Boolean Flagsbool:1, 0, t/T, f/F, true/True/TRUE, false/False/FALSE
Integer Flagsint、uint,int64、uint64,any valid integer, including negative numbers
Float Flagsfloat64,any valid floating-point number
String Flagsstring,any valid string
Time Flags

duration,any valid duration string, such as 100ms, 1h, 1h30m, with supported units: 

h (hours), m (minutes), s (seconds), ms (milliseconds), us (microseconds), ns (nanoseconds)

 

Defining Command-line Parameters

Method 1: flag.Type(flagName, defaultValue, usage) *Type - This method returns a pointer to the corresponding type.

Method 2: flag.TypeVar(p *Type, flagName, defaultValue, usage) - This method accepts a pointer to the variable that will hold the flag's value.

After defining the command-line flags, you need to call flag.Parse() to parse the command-line arguments. Supported command-line argument formats:

  1. -flag xxx (using a space, with one -)
  2. --flag xxx (using a space, with two -)
  3. -flag=xxx (using an =, with one -)
  4. --flag=xxx (using an =, with two -)
var project, worker string

flag.StringVar(&project, "project", "", "Project's name")
flag.StringVar(&worker, "worker", "", "Worker's name")

flag.Parse()

#$ go run consumer.go --help
# -project string
#       Project's name
# -worker string
#      Worker's name

The flag package automatically handles these formats, allowing users to provide command-line parameters in a flexible manner. Once flag.Parse() is called, the flags and their values can be accessed through the variables or pointers defined during flag creation.

Take a break

👉👉👉 【BTTH Year EP100】Xiao Yan and Nalan Yanran pass the sonic wave formation