How to pass boolean arguments to go flags
Asked Answered
S

1

23

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?

Sekofski answered 10/12, 2014 at 22:3 Comment(0)
S
59

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.

Sekofski answered 10/12, 2014 at 22:5 Comment(7)
well usually you set -debug and it becomes true and you don't set it to make the flag false. -debug=false is not necessary if the default is falseSternutatory
@IsmailBadawi: its stated in the doc (and you know what they say about hindsight), but not really explained. This behavior is inconsistent - and thus confusing. Why should booleans be different from strings?Sekofski
@fabrizioM - I suspect you missed the point here: Its not about debug as such; Its about boolean flags in general :]Sekofski
@Sekofski As far as I know you can't omit the argument from string flags, so you don't run into the same problemUnderneath
As @fabrizioM said, boolean flags are a particular case because the presence of such a flag without an argument implies that the flag is true. Specifying for example a filename after such a flag and have it used as the flag's value would conflict with the intent of the flag, which is more of a on/off switch. That's why it makes sense that its default value, when not present, should be false.Pen
@Pen (and IsmailBadawi) - I see you point and I still think its needlessly inconsistent and violates the principle of least astonishment. Thanks for clearing that up, though.Sekofski
I agree that the Go flag package is not exactly the best. There are a few alternatives on github that follow the getopt philosophy more closely. Go's flag, as I understand, inherits some sort of plan9 tradition of handling the command line seen in man.cat-v.org/plan_9/8/getflags.Pen

© 2022 - 2024 — McMap. All rights reserved.