0

cmd is an instance of instance of a *Command struct in the form of:

type Command struct {
  Run func(cmd *Command, args []string)
  Flag flag.FlagSet

  Usage string
  Short string
  Long string
}

The problem that I am running into is that:

if err := cmd.Flag.Parse(args[1:]); err != nil {
  os.Exit(2)
}

Is returning the an err which reads: flag needs an argument: -list when I run my program. Here's how I have my flag setup:

func init() {
  cmdAddSensor.Flag.String("list", "default", "List all of the supported sensors")
}

Which follows the documentation here. I'm confused because the flag command line syntax mentions that any of these forms will work:

-flag
-flag=x
-flag x  // non-boolean flags only

When I run my executable with another argument (i.e.: ./myexecutable blah -list garbage my flag works as expected. I'm trying to understand why line 892 of the flag package's source is getting triggered by my setup.

I'm a Go newbie, so it's possible I'm missing something pretty obvious here. Thanks in advance!

Pavan Ravipati
  • 1,890
  • 14
  • 21
  • 1
    From that last part, is says to me that the 0 index in `args` is actually the first argument, rather than the name of the executable (as is the case usually). Are you _sure_ the first index is the executable name? Print out your args before trying to parse them to double check. – Kaedys Dec 07 '17 at 17:53
  • @Kaedys I think I may have misspoken—the 0 index in `args` isn't `myexecutable`. It's `blah` (in my example above). index 1 is `-list` and index 2 is `garbage` – Pavan Ravipati Dec 07 '17 at 18:02
  • Ah. Well, `-list` is a string. The `-flag` format is only really valid for booleans (where it sets the boolean to `true`). The string form would be `-flag value`, or `-flag ""` if you want to make it explicitly empty. – Kaedys Dec 07 '17 at 18:33
  • Kinda has to be that way, incidentally. Otherwise, what is the result of `-list -foo -bar`? Is the second argument the value of `-list`, or is it the `-foo` flag itself, and `-list` is supposed to be empty? That type of ambiguity is why `-boolflag false` isn't allowed. – Kaedys Dec 07 '17 at 18:35
  • @Kaedys aha! You're absolutely right, and thanks for your follow up explanation. It helped clear it up in my head. using `Flag.Bool` made it so that I could use a flag without an argument. New line: `cmdAddSensor.Flag.Bool("list", true, "List all of the supported sensors")` – Pavan Ravipati Dec 07 '17 at 19:17

0 Answers0