How to pass boolean arguments to go flags

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

How to pass boolean arguments to go flags

问题

我有一个简单的布尔标志,我希望将参数传递给它:

import (
    "flag"
    ...
)

var debugMode = flag.Bool("debug", false, "run in debug mode")
flag.Parse()
if *debugMode == true {
    // 打印一些内容
}

这段代码可以编译和运行,但是这个变量始终为true。我使用以下命令进行调用:

my_application -debug false

但它始终为false。我做错了什么?

英文:

I have a simple boolean flag I wish to pass args to:

import (
    "flag"
    ...
 )

var debugMode = flag.Bool("debug", false, "run in debug mode")
flag.Parse()
if *debugMode == true {
    //print something
}

This code compiles and runs - but the variable is always true. I use the following call:

my_application -debug false

and it's never false. What am I doing wrong?

答案1

得分: 50

我在这上面花了一个小时。结果发现指定布尔参数的格式是:

my_application -debug=false -another_boolean_param=boolean_value

而不是问题中所述的方式。这很棘手:非布尔参数不需要使用"="字符。

英文:

I spent a good hour on this. Turns out the format for specifying boolean args is:

my_application -debug=false -another_boolean_param=boolean_value

and not as stated in the question. This is tricky: non boolean parameters do NOT require the "=" character.

huangapple
  • 本文由 发表于 2014年12月11日 06:03:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/27411691.html
匿名

发表评论

匿名网友

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

确定