简介:

用来解析命令行参数

使用

var name string
var age int
var rich bool

func init(){
//定义接收命令行接收的参数
flag.StringVar(&name,"name","everyone","The greting object")
flag.IntVar(&age,"age",18,"the object age")
flag.BoolVar(&rich,"rich",true,"是土豪")
}
func main(){

flag.Parse() //函数flag.Parse用于真正解析命令参数,在定义参数之后和使用之前必须调用。
fmt.Printf("hello,%s!年龄:%d,土豪:%v\n",name,age,rich)

}

使用说明

D:\TEST\gopath\src\awesomeProject\flag_s>go run start.go --help
Usage of C:\Users\ADMINI~1\AppData\Local\Temp\go-build2699435114\b001\exe\start.exe:
-age int
the object age (default 18)
-name string
The greting object (default "everyone")

自定义Usage of XXX

var name string
var age int
/*
ErrorHandling defines how FlagSet.Parse behaves if the parse fails.type ErrorHandling int These constants cause FlagSet.Parse to behave as described if the parse fails.
const (
ContinueOnError ErrorHandling = iota // Return a descriptive error.
ExitOnError // Call os.Exit(2) or for -h/-help Exit(0).
PanicOnError // Call panic with a descriptive error.
)
*/
var newcmdline=flag.NewFlagSet("question",flag.ExitOnError)

func init() {
newcmdline.StringVar(&name,"name","","姓名")
newcmdline.IntVar(&age,"age",18,"年龄")
}
func main() {
newcmdline.Parse(os.Args[1:])
fmt.Printf("hello!%s,年龄:%d",name,age)
}

验证自定义说明

D:\TEST\gopath\src\awesomeProject\flag_s>go run start.go --help
Usage of question:
-age int
年龄 (default 18)
-name string
姓名

自定义help头源码依据

NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
f := &FlagSet{
name: name,
errorHandling: errorHandling,
}
f.Usage = f.defaultUsage
return f
}

ErrorHandling defines how FlagSet.Parse behaves if the parse fails.type ErrorHandling int These constants cause FlagSet.Parse to behave as described if the parse fails.
const (
ContinueOnError ErrorHandling = iota // Return a descriptive error.
ExitOnError // Call os.Exit(2) or for -h/-help Exit(0).
PanicOnError // Call panic with a descriptive error.
)


Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.
func Parse() {
// Ignore errors; CommandLine is set for ExitOnError.
CommandLine.Parse(os.Args[1:])
}