golang:如何将pflag与其他使用flag的软件包一起使用?

How does one use pflag while also using other packages that use flag?

Some of these packages define flags for the flag package (e.g. in their init functions) - and require flag.Parse() to be called.

Defining flags using the pflag package, require pflag.Parse() to be called.

One of the calls to flag.Parse() and pflag.Parse() will fail when arguments are mixed.

How does one use pflag with other packages that use flag?

I got a response from a maintainer for pflag.

The solution is to "import" all flags defined for flag into pflag, and then make a call to pflag.Parse() alone.

pflag provides a convenience function called AddGoFlagSet() to accomplish this.

How does one use pflag with other packages that use flag?

You cannot. It is either or. plfag is a drop-in replacement for flag, not an addon.

I have found two approach for this.

  1. One with pflags AddGoFlags(). IE.

    f := pflag.NewFlagSet("goFlags", pflag.ExitOnError)
    f.AddGoFlagSet(flag.CommandLine)
    f.Parse([]string{
       "--v=10", // Your go flags that will be pass to other programs.
    })
    flag.Parse()
    
  2. Another approach you can use. This is not by the book but i have seen some used this.. get the flag valu by another pflag.

    pflag.StringVar(&f, "f", "**", "***")
    pflag.Parse()
    

Set the value as flag value.

    flag.Set("v", f)
    flag.Parse()

and you are good to go..