func testFlag() {
arg1 := flag.String("p1", "arg1 default value", "arg1 description help")
arg2 := flag.String("p2", "arg2 default value", "arg2 description help")
arg3 := flag.Bool("p3", true, "arg3 description help")
flag.Parse()
var cmd string = flag.Arg(0)
fmt.Printf("action : %s\n", cmd)
fmt.Printf("arg1 : %s\n", *arg1)
fmt.Printf("arg2 : %s\n", *arg2)
fmt.Printf("arg3 : %v\n", *arg3)
fmt.Printf("-------------------------------------------------------\n")
fmt.Printf("there are %d non-flag input param\n", flag.NArg())
for i, param := range flag.Args() {
fmt.Printf("#%d :%s\n", i, param)
}
}
使用: 查看输入参数格式:-h和-help一样
PS C:\Code\Go\src\test> ./test.exe -h
Usage of C:\Code\Go\src\test\test.exe:
-p1 string
arg1 description help (default "arg1 default value")
-p2 string
arg2 description help (default "arg2 default value")
-p3
arg3 description help (default true)
PS C:\Code\Go\src\test> ./test.exe -help
Usage of C:\Code\Go\src\test\test.exe:
-p1 string
arg1 description help (default "arg1 default value")
-p2 string
arg2 description help (default "arg2 default value")
-p3
arg3 description help (default true)
PS C:\Code\Go\src\test>
可以修改-h -help的信息:
flag.Usage = func() { fmt.Println("you can change the help input content by modify Usage func") }
flag.Parse()
PS C:\Code\Go\src\test> .\test.exe -h
you can change the help input content by modify Usage func
PS C:\Code\Go\src\test> .\test.exe -help
you can change the help input content by modify Usage func
PS C:\Code\Go\src\test>
default:
PS C:\Code\Go\src\test> ./test.exe
action :
arg1 : arg1 default value
arg2 : arg2 default value
-------------------------------------------------------
there are 0 non-flag input param
参数未定义(只能识别-p1 -p2 -p3 不能识别-p)
PS C:\Code\Go\src\test> ./test.exe -p a
flag provided but not defined: -p
Usage of C:\Code\Go\src\test\test.exe:
-p1 string
arg1 description help (default "arg1 default value")
-p2 string
arg2 description help (default "arg2 default value")
-p3
arg3 description help (default true)
修改-p1参数的默认值为a
PS C:\Code\Go\src\test> ./test.exe -p1 a
action :
arg1 : a
arg2 : arg1 default value
arg3 : true
-------------------------------------------------------
there are 0 non-flag input param
输入了没有flag标识的参数(无-,可以获取到p1a值)
PS C:\Code\Go\src\test> ./test.exe p1a
action : p1a
arg1 : arg1 default value
arg2 : arg1 default value
arg3 : true
-------------------------------------------------------
there are 1 non-flag input param
#0 :p1a
参考:https://studygolang.com/articles/4742