Home > Backend Development > Golang > How to Properly Define and Parse Independent FlagSets in Go for Subcommands?

How to Properly Define and Parse Independent FlagSets in Go for Subcommands?

Barbara Streisand
Release: 2024-12-11 04:43:08
Original
544 people have browsed it

How to Properly Define and Parse Independent FlagSets in Go for Subcommands?

Defining Independent FlagSets in GoLang

The Go documentation states that the FlagSet type allows the creation of independent sets of flags, which is useful for implementing subcommands in a command-line interface. However, implementing this functionality can be challenging.

When defining two FlagSets, parsing one of them may result in errors or warnings if the command line contains flags intended for the second FlagSet. For instance, consider the following code:

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)
}
Copy after login

Executing cmd -apply or cmd -reset generates various warnings. This behavior is due to the lack of differentiation between subcommands. To separate these FlagSets effectively, it is necessary to distinguish the subcommands first and then parse the correct FlagSet.

An example of how to achieve this:

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)
    }
}
Copy after login

This code allows the -silent flag to be used exclusively with the apply subcommand and the -loud flag to be used exclusively with the reset subcommand.

The above is the detailed content of How to Properly Define and Parse Independent FlagSets in Go for Subcommands?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template