TOC

Golang: 命令行参数解析(flag

Go 自带 flag 包,可以用于解析命令行参数。但用起来非常繁琐,更谈不上优雅,远不如 Python 的 argparse 包简洁明了,易于使用。

语法

类型

  • flag.Flag
  • flag.FlagSet
  • flag.Getter
  • flag.Value

方法

func Bool(name string, value bool, usage string) *bool
func BoolVar(p *bool, name string, value bool, usage string)

func Duration(name string, value time.Duration, usage string) *time.Duration
func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

func Float64(name string, value float64, usage string) *float64
func Float64Var(p *float64, name string, value float64, usage string)

func Func(name, usage string, fn func(string) error)

func Int(name string, value int, usage string) *int
func IntVar(p *int, name string, value int, usage string)

func Int64(name string, value int64, usage string) *int64
func Int64Var(p *int64, name string, value int64, usage string)

func String(name string, value string, usage string) *string
func StringVar(p *string, name string, value string, usage string)

func Uint(name string, value uint, usage string) *uint
func UintVar(p *uint, name string, value uint, usage string)

func Uint64(name string, value uint64, usage string) *uint64
func Uint64Var(p *uint64, name string, value uint64, usage string)

func Var(value Value, name string, usage string)
func Arg(i int) string  // i-th argument
func Args() []string    // non-flag arguments

func NArg() int         // number of arguments remaining after flags have been processed
func NFlag() int        // number of command-line flags that have been set

func Parse()
func Parsed() bool
func Set(name, value string) error

func PrintDefaults()    // 帮助信息
func UnquoteUsage(flag *Flag) (name string, usage string)  // 返回 flag 的名称和用法

func Visit(fn func(*Flag))
func VisitAll(fn func(*Flag))

type ErrorHandling

FlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

上面的方法 FlagSet 也都有一份。

示例:Todo


参考资料与拓展阅读