[Go] flag package command line parameter analysis

In the Go language, flagthe package provides the function of command line parameter parsing, which can conveniently obtain input parameters from the command line. Using flagthe package, you can define command-line arguments, and parse user-supplied argument values.

Here is flagan example of a package:

package main

import (
	"flag"
	"fmt"
)

func main() {
	// 定义命令行参数
	name := flag.String("name", "guest", "请输入你的名字")
	age := flag.Int("age", 18, "请输入你的年龄")
	married := flag.Bool("married", false, "请输入你的婚姻状况")

	// 解析命令行参数
	flag.Parse()

	// 输出命令行参数的值
	fmt.Println("名字:", *name)
	fmt.Println("年龄:", *age)
	fmt.Println("婚姻状况:", *married)
}

Compile and run the above code, execute the command go run main.go -name Alice -age 25 -married=true, the output is as follows:

 In the example, we first use the flag.String(), flag.Int()and flag.Bool()methods to define three command-line parameters corresponding to string, integer and Boolean values. The first argument to these methods is the name of the command-line argument, the second argument is the default value, and the third argument is the argument's description.

Then, we call flag.Parse()the method to parse the command-line arguments so that we can get the user-supplied argument values ​​in code.

Finally, we use *name, *ageand *marriedto get the value of the corresponding command line parameter and output it to the console.

You can define more command line parameters as needed, and perform corresponding logical processing in the code according to the parameter values.

Guess you like

Origin blog.csdn.net/fanjufei123456/article/details/129683535