Home > Backend Development > Golang > How to Implement Independent Flag Sets for Subcommands in Go?

How to Implement Independent Flag Sets for Subcommands in Go?

Susan Sarandon
Release: 2025-01-01 00:08:10
Original
739 people have browsed it

How to Implement Independent Flag Sets for Subcommands in Go?

Independent Flag Sets in GoLang

The Go documentation for the flag package states that it allows for the definition of independent sets of flags, suitable for implementing subcommands in a command-line interface. However, the question arises as to how to achieve this functionality.

In a scenario where two FlagSet objects are defined, parsing one may result in errors and warnings if the command line contains flags intended for the other. The following example illustrates this issue:

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

This code produces warnings when trying to execute cmd -apply or cmd -reset. The goal is to maintain separate FlagSet objects, ensuring that -silent only works for -apply.

The solution lies in distinguishing the subcommands and then calling Parse on the appropriate FlagSet. The revised code:

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

With this approach, only the relevant FlagSet will be parsed based on the specified subcommand, ensuring the desired behavior.

The above is the detailed content of How to Implement Independent Flag Sets for Subcommands in Go?. 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