简体   繁体   English

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

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

I have read the docs for the following two libraries used to create flags. 我已经阅读了用于创建标志的以下两个库的文档。 :

  1. https://golang.org/pkg/flag/ https://golang.org/pkg/flag/
  2. https://github.com/codegangsta/cli 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 : 根据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 并执行:$ ./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 任何指导将不胜感激,谢谢

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. 通过此更改, fork标志将按fork工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM