Is it possible not to set default value in flag package in Go? For example, in flag package you can write out the following line:
filename := flag.String("file", "test.csv", "Filename to cope with")
In the above code, I don't want to necessarily set default value, which is test.csv
in this case, and instead always make users specify their own filename, and if it's not specified then I want to cause an error and exit the program.
One of the way I came up with is that I first check the value of filename
after doing flag.Parse()
, and if that value is test.csv
then I have the program exits with the appropriate error message. However, I don't want to write such redundant code if it can be evaded - and even if it can't, I'd like to hear any better way to cope with the issue here.
You can do those kind of operations in Python's argparse
module by the way - I just want to implement the similar thing if I can...
Also, can I implement both short and long arguments (in other words both -f
and -file
argument?) in flag package?
Thanks.
Using the flag package involves three steps: First, define variables to capture flag values, then define the flags your Go application will use, and finally, parse the flags provided to the application upon execution.
Command-line flags Bool() , flag.Int() , etc. After you've defined your flags, you need to call flag. Parse() . This call will execute command-line parsing and will let you use the flags.
Golang has a built-in package called flag that enables one to parse command-line flags. The flag package allows you to define String , Bool , or Int flags. To be able to access the parameters passed as arguments to the command line execution of your program, three steps need to be completed.
I think it's idiomatic to design your flag values in such a way which implies "not present" when equal to the zero value of their respective types. For example:
optFile := flag.String("file", "", "Source file") flag.Parse() fn := *optFile if fn == "" { fn = "/dev/stdin" } f, err := os.Open(fn) ...
Ad the 2nd question: IINM, the flag package by design doesn't distinguish between -flag
and --flag
. IOW, you can have both -f
and --file
in your flag set and write any version of -
or --
before both f
and file
. However, considering another defined flag -g
, the flag package will not recognize -gf foo
as being equvalent of -g -f foo
.
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