英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论