Defining Independent FlagSets in GoLang

前端 未结 2 1261
野趣味
野趣味 2020-12-09 16:59

The Go documentation (http://golang.org/pkg/flag/) says:

The FlagSet type allows one to define independent sets of flags, such as to implement subcomm

相关标签:
2条回答
  • 2020-12-09 17:03

    You are meant to distinguish between subcommands first, and then call Parse on the right FlagSet.

    f1 := flag.NewFlagSet("f1", flag.ContinueOnError)
    silent := f1.Bool("silent", false, "")
    f2 := flag.NewFlagSet("f2", flag.ContinueOnError)
    loud := f2.Bool("loud", false, "")
    
    switch os.Args[1] {
      case "apply":
        if err := f1.Parse(os.Args[2:]); err == nil {
          fmt.Println("apply", *silent)
        }
      case "reset":
        if err := f2.Parse(os.Args[2:]); err == nil {
          fmt.Println("reset", *loud)
        }
    }
    

    http://play.golang.org/p/eaEEx_EReX

    0 讨论(0)
  • 2020-12-09 17:22

    Just change these code

    if err := f2.Parse(os.Args[1:]); err == nil {
        fmt.Println(*reset)
    }
    

    to

    f2.Parse(os.Args[1:])
    fmt.Println(*reset)
    

    but the warning is just left on the console.if u wanna remove it ,modify /usr/local/go/src/flag/flag.go and recompile the golang .. or do a copy of flag package.

      →_→ 怀疑的眼神~~

    0 讨论(0)
提交回复
热议问题