Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can command line flags in Go be set to mandatory?

Is there a way how to set that certain flags are mandatory, or do I have to check for their presence on my own?

like image 538
Petr Avatar asked Aug 03 '15 11:08

Petr


People also ask

How do you use flags in Golang?

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.

How do you pass command-line arguments in Golang?

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.

What is command-line flag parsing?

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.


1 Answers

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.

like image 180
icza Avatar answered Sep 20 '22 06:09

icza