Restricting arg values in Go

16 Apr 2021

Using the flag.Value interface is a nice way of offloading flag parsing to each flag type, and keeping the main function tidier. Here's an example:

// ConsoleType is a type that implements the flag.Value interface of String() and Set(string)
type ConsoleType string

func (s *ConsoleType) String() string {
  return string(*s)
}

func (s *ConsoleType) Set(value string) error {
  if !(value == "XBox" || value == "PlayStation" || value == "Wii") {
    return fmt.Errorf(`"%s" is not one of "XBox", "PlayStation", or "Wii"`, value)
  }
  *s = ConsoleType(value)
  return nil
}

func main() {
  var consoleType ConsoleType = ConsoleType("XBox")
  flag.Var(&consoleType, "placetype", `One of "XBox", "PlayStation", or "Wii"`)

  flag.Parse()

  fmt.Printf("Console type is %s\n", consoleType.String())
}

One could imagine doing this for dates (where the command-line string needs to be parsed) and all kinds of other stuff.