Parsing Golang syntax after command line argument
I am parsing command line arguments. I am using the following code:
var flagB = flag.Bool("b", false, "boolflag")
func main() {
flag.Parse()
fmt.Println(flag.NArg())
fmt.Println("-b", *flagB)
}
When I execute binary like this:
> test -b "random"
I get the expected result because there is one argument and the flag is set:
1
-b true
However, when I execute the binary, the opposite is true:
> test "random" -b
I get this:
2
-b false
Now the flag is no longer restored as a flag, but as another argument.
Why is that? Is there a definition that flags are first followed by arguments? I always thought that "the argument passing and parsing arguments is" GNU-way ": The first places after binary are reserved for required arguments. And after that you can supply optional arguments and flags.
source to share
The package flag
does not use the GNU parsing rules. The rules are explained in the documentation for the package flag . Your question was answered by:
Fragment parsing stops just before the first non-flag argument ("-" is an argument without a flag) or after the "-" terminator.
source to share