import "github.com/spf13/pflag" var myFlag bool pflag.BoolVarP(&myFlag, "my-flag", "m", false, "Description of my flag") pflag.Parse() if myFlag { // Do something if flag is set } else { // Do something if flag is not set }
import ( "fmt" "github.com/spf13/pflag" ) var fs1, fs2 *pflag.FlagSet var debug bool func init() { fs1 = pflag.NewFlagSet("fs1", pflag.ExitOnError) fs2 = pflag.NewFlagSet("fs2", pflag.ExitOnError) fs1.BoolVarP(&debug, "debug", "d", false, "Enable debug mode") fs2.BoolVarP(&debug, "debug", "d", false, "Enable debug mode") } func main() { fs1.Parse([]string{"-d"}) fs2.Parse([]string{"--debug"}) fmt.Println(debug) // Output: true }In this example, two FlagSets are created to handle different sets of command-line arguments. Both FlagSets define a boolean flag named "debug" using the `BoolVarP` function. The `init()` function is used to initialize the FlagSets, and the `main()` function calls `fs1.Parse()` and `fs2.Parse()` with different sets of arguments. Since both FlagSets define the same flag, the last one to be parsed will take effect. In this case, both `fs1.Parse()` and `fs2.Parse()` set the `debug` variable to true, so the final output is `true`.