Defining Independent FlagSets in GoLang

匿名 (未验证) 提交于 2019-12-03 01:16:02

问题:

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

The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface.

I need this functionality but I can't figure out how to persuade the flag pkg to do it. When I define two FlagSets, parsing one of them will give me errors and warnings if the commandline has flags that are meant for the second one. Example:

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

I get all sorts of warnings if I try to do cmd -apply OR cmd -reset. I want to keep these FlagSets separate because I want to only have -silent work for -apply.

What am I missing?

回答1:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!