Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass boolean arguments to go flags

Tags:

flags

go

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?

like image 902
FuzzyAmi Avatar asked Dec 10 '14 22:12

FuzzyAmi


People also ask

How do you use boolean flag?

 A Flag is a boolean variable that signals when some condition exists in a program.  When a flag is set to true, it means some condition exists  When a flag is set to false, it means some condition does not exist. if(score > 95) highscore = true;  Here, highscore is a flag indicating that the score is above 95.

How do you pass the flag in Golang?

Any tag not defined in the program can be stored and accessed using the flag. Args() method. You can specify the flag by passing the index value i to flag. Args(i) .

Are boolean flags bad?

Flags are not a best practice because they reduce the cohesion of a function. It does more than one thing. Booleans make it hard to understand what a function does based on the call site. Single argument functions and passing an object with named values improves the readability.


1 Answers

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.

like image 197
FuzzyAmi Avatar answered Oct 14 '22 05:10

FuzzyAmi