是否可以覆盖标志值?

I'm wondering if it's possible to overwrite flag values on runtime.

Example:

  • main.go imports a package pkg.go.
  • pkg.go uses a flag ("-myFlag") but the identifier which stores the flag is not exported.

Is it possible to change the flag value of "-myFlag" which pkg.go receives from main.go ?

Usecase: I'm using a library which uses glog to log the errors. glog uses flags to define where to write the logs and by default it writes the logs to a file. The environment I'm using doesn't allow writes to filesystem nor to set flags on app initialisation so I need to overwrite/set the glog flags somehow so that I can set it to write the errors to stderr.

You can just do flag.Set("flagname", "whatever").

Or if you want to do something else to the option (check the default, see if it's already been changed, etc) you can use f := flag.Lookup("flagname") and then f.Value.Set("whatever") (as well as other methods).

In either case there are matching flag.FlagSet methods if you need this on something other than the flag.CommandLine set.

Playground example