In this shot, we learn how to check if a command-line flag has been set in Go. For this, we use the flag.Visit()
function in Go.
func Visit(fn func(*Flag))
fn func(*Flag)
: Visit
calls the fn
for each of the flags that are set.
func isFlagPassed(name string) bool {
found := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
In the code snippet above, we see a helper function that uses the flag.Visit()
method. This function needs to be called after the flag.Parse()
method.
package mainimport ("flag""fmt""os")// Define the flagvar help = flag.Bool("help", false, "Show help")var boolFlag = falsevar stringFlag = "Hello There!"var intFlag intfunc main() {// Bind the flagflag.BoolVar(&boolFlag, "boolFlag", false, "A boolean flag")flag.StringVar(&stringFlag, "stringFlag", "Hello There!", "A string flag")flag.IntVar(&intFlag, "intFlag", 4, "An integer flag")// Parse the flagflag.Parse()if !isFlagPassed("boolFlag") {fmt.Println("BoolFlag is not passed !!!")}// Usage demoif *help {flag.Usage()os.Exit(0)}fmt.Println("Boolean Flag is ", boolFlag)fmt.Println("String Flag is ", stringFlag)fmt.Println("Int Flag is ", intFlag)}func isFlagPassed(name string) bool {found := falseflag.Visit(func(f *flag.Flag) {if f.Name == name {found = true}})return found}
boolFlag
is present.flag.Visit()
to check if the flag has been set.Upon execution, the code above prints the statement BoolFlag is not passed !!!
as the output. This is because we do not pass any of the flags in the code above.
We will not get this statement as the output if we execute the code from the terminal as follows:
./main -boolFlag=true
Free Resources