Is there a way how to set that certain flags are mandatory, or do I have to check for their presence on my own?
Args() method. You can specify the flag by passing the index value i to flag. Args(i) . To run the code, type go build coffee.go first.
To access all command-line arguments in their raw format, we need to use Args variables imported from the os package . This type of variable is a string ( [] ) slice. Args is an argument that starts with the name of the program in the command-line. The first value in the Args slice is the name of our program, while os.
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.
The flag
package does not support mandatory or required flags (meaning the flag must be specified explicitly).
What you can do is use sensible default values for (all) flags. And if a flag is something like there is no sensible default, check the value at the start of your application and halt with an error message. You should do flag value validation anyway (not just for required flags), so this shouldn't mean any (big) overhead, and this is a good practice in general.
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