With the flag package, is there a good way to distinguish if a string flag was passed?
For example, when the flag is not passed, I want to set it to a dynamic default value. However, I want to set it to empty if the flag was provided but with a value of ""
.
Current I am doing the following:
flagHost = flag.String(flagHostFlagKey, "", "...") ... setHostname := false for _, arg := range os.Args { if arg == "-"+flagHostFlagKey { setHostname = true } } if !setHostname { ...
Which seems to work fine, but is kind of ugly. Is there a better way while staying with the standard flag package?
In Golang, flag is a built-in package shipped with Go standard library. A flag is a formatted string that is passed as an argument to a program so that, according to the flag passed, the control or behavior of the program has some augmented utilities.
Defining flags is easy, you can set them up using flag. String() , flag. Bool() , flag.Int() , etc. After you've defined your flags, you need to call flag.
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag. package main. Go provides a flag package supporting basic command-line flag parsing.
Use the flag.Visit()
function:
func isFlagPassed(name string) bool { found := false flag.Visit(func(f *flag.Flag) { if f.Name == name { found = true } }) return found }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With