Go语言内置的flag包实现了命令行参数的解析,flag包使得开发命令行工具更为简单
1.os.Args
简单的想要获取命令行参数,可以使用os.Args来获取命令行参数
os.Args是一个存储命令行参数的字符串切片,它的第一个元素是执行文件的名称
//os.Args是一个[]string
if len(os.Args) > 0 {
for index, arg := range os.Args {
fmt.Printf("args[%d]-%v\n",index,arg)
}
}
2.flag包基本使用
2.1flag参数类型
flag包支持的命令行参数类型有bool、int、int64、uint、uint64、float float64、string、duration
2.2定义命令行flag参数
flag.Type()
flag.Type(flag名, 默认值, 帮助信息)*Type
name := flag.String("name","cheng","姓名")
age := flag.Int("age",18,"年龄")
married := flag.Bool("married",false,"婚否")
delay := flag.Duration("d",0,"时间间隔")
fmt.Println(*name,*age,*married,*delay) //cheng 18 false 0s
flag.TypeVar()
flag.TypeVar(Type指针, flag名, 默认值, 帮助信息)
var name string
var age int
var married bool
var delay time.Duration
flag.StringVar(&name,"name","cheng","姓名")
flag.IntVar(&age,"age",18,"年龄")
flag.BoolVar(&married,"married",false,"婚否")
flag.DurationVar(&delay,"d",0,"时间间隔")
fmt.Println(name,age,married,delay) //cheng 18 false 0s
2.3flag.Parse()
定义好命令行flag参数后,需要通过调用flag.Parse()来对命令行参数进行解析
flag.Parse() //解析命令行参数
2.4flag其他函数
flag.Args() //返回命令行参数后的其他参数,以[]string类型
flag.NArg() //返回命令行参数后的其他参数个数
flag.NFlag() //返回使用的命令行参数个数
var name string
var age int
var married bool
var delay time.Duration
flag.StringVar(&name,"name","cheng","姓名")
flag.IntVar(&age,"age",18,"年龄")
flag.BoolVar(&married,"married",false,"婚否")
flag.DurationVar(&delay,"d",0,"时间间隔")
//解析命令行参数
flag.Parse()
//fmt.Println(name,age,married,delay) //cheng 18 false 0s
fmt.Println(flag.Args())
fmt.Println(flag.NArg())
fmt.Println(flag.NFlag())