为什么 FlagSet 无法正确解析这些参数?

huangapple go评论86阅读模式
英文:

Why is a FlagSet not correctly parsing these args?

问题

这是一个简化的代码片段:在一个真实项目中的上下文是,我有一个命令行应用程序,它解析输入到程序的参数,然后是解析命令名后剩余参数的各个命令。我为每个命令使用了一个FlagSet,但由于某种原因,它永远无法解析出标志:

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)
}

我期望的输出是:[arg] value,但实际上我得到的是:[arg -flag value] defaultValue

代码:http://play.golang.org/p/D4RKPpVODF

我在这里做错了什么?

英文:

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?

答案1

得分: 4

你的args数组中的参数顺序是错误的。非标志参数必须在标志参数之后。所以你应该这样写:

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

然后输出就是你期望的:

[arg] value

代码:http://play.golang.org/p/cv972SLZfG

英文:

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

huangapple
  • 本文由 发表于 2014年8月12日 00:27:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/25247990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定