如何在Go CLI程序中输入没有参数的可选标志

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

How to enter an optional flag with no parameters in Go CLI program

问题

我已阅读了用于创建标志的以下两个库的文档:

  1. https://golang.org/pkg/flag/
  2. https://github.com/codegangsta/cli

但是我没有找到设置可选标志的方法。如何实现可选标志呢?

根据来自 https://gobyexample.com/command-line-flags 的代码:

package main
import "flag"
import "fmt"

func main() {
  boolPtr := flag.Bool("fork", false, "a bool")
  fmt.Println("fork:", *boolPtr)
}

并通过以下方式执行:
$ ./command-line-flags -fork

应该得到 true,这是我想要的行为,但是在我的机器上却得到了 false。

如果有任何指导,将不胜感激。
谢谢。

英文:

I have read the docs for the following two libraries used to create flags. :

  1. https://golang.org/pkg/flag/
  2. https://github.com/codegangsta/cli

And have not come across a way to do optional flags. How can this be done?

According to the code from https://gobyexample.com/command-line-flags :

package main
import "flag"
import "fmt"

func main() {
  boolPtr := flag.Bool("fork", false, "a bool")
  fmt.Println("fork:", *boolPtr)
}

and executed by :
$ ./command-line-flags -fork

Should result in true, this is the behavior I desire but I am getting false on my machine.

Any guidance would be appreciated,
Thanks

答案1

得分: 19

在定义所有标志之后并在访问标志之前,您必须解析标志

func main() {
  boolPtr := flag.Bool("fork", false, "a bool")
  flag.Parse()  // 添加这一行
  fmt.Println("fork:", *boolPtr)
}

通过这个改变,fork标志将按预期工作。

英文:

You must parse the flags after all flags are defined and before flags are accessed:

func main() {
  boolPtr := flag.Bool("fork", false, "a bool")
  flag.Parse()  // add this line
  fmt.Println("fork:", *boolPtr)
}

With this change, the fork flag will work as desire.

huangapple
  • 本文由 发表于 2015年12月21日 11:35:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/34388593.html
匿名

发表评论

匿名网友

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

确定