Can command line flags in Go be set to mandatory?

Petr picture Petr · Aug 3, 2015 · Viewed 30.1k times · Source

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

Answer

icza picture icza · Aug 3, 2015

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.