How to check if a command-line flag is set in Go
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.
Syntax
func Visit(fn func(*Flag))
Parameter
fn func(*Flag): Visit calls the fn for each of the flags that are set.
Function
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.
Example
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}
Explanation
- Lines 10 to 13: We declare the flags.
- Lines 17 to 19: We bind these flags.
- Line 22: We parse the flags.
- Line 24: We check if the
boolFlagis present. - Lines 38 to 46: The helper function uses
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
Attributions:
- undefined by undefined