Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
communitycreator

How to check if a command-line flag is set in Go

Anjana Shankar

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 main

import (
	"flag"
	"fmt"
	"os"
)

// Define the flag
var help = flag.Bool("help", false, "Show help")
var boolFlag = false
var stringFlag = "Hello There!"
var intFlag int

func main() {
	// Bind the flag
	flag.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 flag
	flag.Parse()

	if !isFlagPassed("boolFlag") {
		fmt.Println("BoolFlag is not passed !!!")
	}
	// Usage demo
	if *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 := false
	flag.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 boolFlag is 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

RELATED TAGS

go
communitycreator
RELATED COURSES

View all Courses

Keep Exploring