Standard library flag in golang

The flag package built in Go language realizes the analysis of command line parameters. The flag package makes it easier to develop command line tools.

os.Args

If you simply want to get command line parameters, you can use os.Args to get command line parameters like the following code example.

func main() {
	// Get command line parameters
	// os.Args: []string
	if len(os.Args) > 0 {
		for i, v := range os.Args {
			fmt.Println(i, v)
		}
	}
}

Execute the command: go run. \ main.go host: 127.0.0.1 port: 8080
Output results:

0 C:\Users\mayanan\AppData\Local\Temp\go-build3549800423\b001\exe\main.exe
1 host:127.0.0.1
2 port:8080

os.Args is a string slice that stores command-line parameters, and its first element is the name of the execution file.

flag package basic usage

  1. flag parameter type
    The command line parameter types supported by flag package include bool, int, int64, uint, uint64, float, float64, string and duration.
flag parameter Effective value
String flag Legal string
Integer flag 1234, 0664, 0x1234 and other types can also be negative numbers.
Floating point flag Legal floating point number
bool type flag 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False.
Time period flag Any valid time period string. Such as "300ms", "1.5h" and "2h45m". Legal units include "ns", "us" / "µ s", "Ms", "s", "m" and "H".

Define command line flag parameters

flag.Type()

The basic format is as follows:
flag.Type(flag name, default value, help information) * type for example, if we want to define three command line parameters: name, age and marriage, we can define them as follows:

func main() {
	// Use of flag.Type()
	name := flag.String("name", "Zhang San", "full name")
	age := flag.Int("age", 18, "Age")
	married := flag.Bool("married", false, "marriage ")
	delay := flag.Duration("d", 0, "time interval")

	flag.Parse()

	fmt.Println(*name, *age, *married, *delay)
}

Terminal input:
go run .\main.go -name lisi --age 88 -married=true --d=15s

Output:
lisi 88 true 15s

flag.TypeVar()

The basic format is as follows: flag.TypeVar(Type pointer, flag name, default value, help information) for example, we want to define three command-line parameters: name, age and marriage. We can define them as follows:

func main() {
	var name string
	var age uint
	var married bool
	var d time.Duration

	flag.StringVar(&name, "name", "Wang Wu", "full name")
	flag.UintVar(&age, "age", 18, "Age")
	flag.BoolVar(&married, "m", false, "marriage ")
	flag.DurationVar(&d, "duration", 0, "time interval")

	flag.Parse()

	fmt.Println(name, age, married, d)

}

Input:
go run .\main.go -name lisi --age 35 -m=true --duration=1h15m36s

Output:
lisi 35 true 1h15m36s

flag.Parse()

After defining the command line flag parameter through the above two methods, you need to parse the command line parameter by calling flag.Parse().

The following command line parameter formats are supported:

-flag xxx (use space, a - symbol)
--flag xxx (use space, two - Symbols)
-flag=xxx (use an equal sign, a - symbol)
--flag=xxx (use equal sign, two - Symbols)
Where boolean type parameters must be specified with an equal sign.

Flag parsing stops before the first non flag parameter (single - "not flag parameter), or after the terminator" – ".

flag other functions

  • flag.Args() / / / return other parameters after the command line parameters, in the form of [] string
  • flag.NArg() / / returns the number of other parameters after the command line parameters
  • flag.NFlag() / / returns the number of command line parameters used

Complete example

func main() {
	var name string
	var age uint
	var married bool
	var d time.Duration

	flag.StringVar(&name, "name", "Wang Wu", "full name")
	flag.UintVar(&age, "age", 18, "Age")
	flag.BoolVar(&married, "m", false, "marriage ")
	flag.DurationVar(&d, "duration", 0, "time interval")

	flag.Parse()

	fmt.Println(name, age, married, d)  // lisi 35 true 1h15m36s

	fmt.Println(flag.Args())  // [abc true 123]
	fmt.Println(flag.NArg())  // 3
	fmt.Println(flag.NFlag())  //  4

}

Input:
go run .\main.go -name lisi --age 35 -m=true --duration=1h15m36s abc true 123

Output:

lisi 35 true 1h15m36s
[abc true 123]
3
4

Posted by turboprop on Mon, 29 Nov 2021 01:09:34 -0800