user3179836
user3179836

Reputation: 23

Why is a FlagSet not correctly parsing these args?

Here's a simplified code snippet: the context for this in a real project is that I have a command-line app that's parsing arguments input to the program, and then individual commands that parse the remaining args after the command name is pulled out. I'm using a FlagSet per command, but for some reason, it won't ever actually parse out flags:

package main

import (
"fmt"
"flag"
)

func main() {
    args := []string{"arg", "-flag", "value"}
    flags := flag.NewFlagSet("flags", flag.ExitOnError)
    flagValue := flags.String("flag", "defaultValue", "")

    flags.Parse(args)
    fmt.Println(flags.Args(), *flagValue)

}

I'd expect the output to be: [arg] value, but instead I get: [arg -flag value] defaultValue

Code: http://play.golang.org/p/D4RKPpVODF

What am I doing wrong here?

Upvotes: 2

Views: 1014

Answers (1)

David Grayson
David Grayson

Reputation: 87416

The arguments in your args array are in the wrong order. The non-flag arguments have to come after the flag arguments. So you should write:

args := []string{"-flag", "value", "arg"}

Then the output is what you expected:

[arg] value

Code: http://play.golang.org/p/cv972SLZfG

Upvotes: 4

Related Questions