Go:命令行标志

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

Go: command line flags

问题

我知道你可以指定命令行标志并对你的二进制文件进行运行,就像这样:

./binary -output=html -type=doc

然而,我正在查看这个Go包的实现:https://github.com/jteeuwen/go-bindata

我想知道作者是如何使用户能够像这样运行命令

go-bindata /data 

而不是

./go-bindata -target=/data

如果我漏掉了什么,请帮忙解答一下!

英文:

I know you can specify command line flags and run your binary file against them like this:

./binary -output=html -type=doc

However, I was looking at the implementation of this Go package: https://github.com/jteeuwen/go-bindata

I'm wondering how the author is able to enable the user to run the commands like this

go-bindata /data 

instead of

./go-bindata -target=/data

Appreciate some help in case I missed out anything!

答案1

得分: 6

关键是使用flag.Args(),它是紧随标志后的非标志参数。你可以获取整个参数列表,或者使用flag.Arg(i)获取特定的参数。请参阅http://golang.org/pkg/flag/#Args

从你发布的程序源代码中可以看到:

// 创建输入配置。
c.Input = make([]bindata.InputConfig, flag.NArg())
for i := range c.Input {
    c.Input[i] = parseInput(flag.Arg(i))
}
英文:

The trick is to use flag.Args() which is, simply, the non flag arguments following the flags. You can either fetch the entire list, or get a specific arg with flag.Arg(i). See http://golang.org/pkg/flag/#Args

And from the source of the program you posted:

// Create input configurations.
c.Input = make([]bindata.InputConfig, flag.NArg())
for i := range c.Input {
	c.Input[i] = parseInput(flag.Arg(i))
}

答案2

得分: 1

使用flag包非常简单。查看flag.Args

英文:

Easy as pie using the flag package. Checkout flag.Args

huangapple
  • 本文由 发表于 2015年2月23日 00:24:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/28660175.html
匿名

发表评论

匿名网友

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

确定