2

I declare a string flag with a default value like this:

animalFlag := flag.String("typeOfAnimal", "Cat", "Type of animal")

I want to force that user could only give a specific string (like "Dog", "Lion") and not some random string like "Rose". How do I enforce this in Go?

icza
  • 389,944
  • 63
  • 907
  • 827
Sloth
  • 21
  • 3

1 Answers1

0

The flag package does not support limiting the valid / accepted set of values for flags.

What you can do is perform flag value validation, and this is a good practice in general: check the value at the start of your application and halt with an error message if the provided value is invalid (according to your arbitrary rules).

See related question: Can command line flags in Go be set to mandatory?

icza
  • 389,944
  • 63
  • 907
  • 827
  • 5
    "The flag package does not support limiting the valid / accepted set of values for flags." One can stick the validation logic into an implementation of the [flag.Value interface](https://golang.org/pkg/flag/#Value), though, producing good error messages: https://play.golang.org/p/eXhFj1DYCzC – Peter Dec 21 '19 at 13:14