0

I have a type with an availability field, which can be one of three values, "available", "unavailable", neither.

type Something struct {
    Name string `json:"Name" yaml:"name"`
    status string `json:"-" yaml:"status"`
}

The type is built from a yaml which can have inputs like,

- name: "standard_thing"
  status: "standard"
- name: "premium_thing"
  status: "premium"
- name: "random_thing

I'm trying to think of the best way to have this status field so it is clear that there are two options or blank. Using a boolean doesn't work because the objects that have no status can be differentiated in this way, in-fact I specifically want the field to be optional so element matching doesn't break on existing entries that don't have this field in the db.
Is the only way to do this really to use strings and then some kind of validation on the string. Or is it better to use a different status type with a couple of booleans, that looks messy in the yaml though, maybe a boolean pointer or somehow aliasing a boolean? Is there a way to use enums that can be input as strings to handle that validation? I wanted to do something like

type status string

const (
   premium status = "premium"
   standard status = "standard"
)

To lock the two input strings, I know the above doesn't work but wondering if there is some idiomatic go way to provide string options/enums where the YAML wouldn't need number inputs?

Richard Wilson
  • 467
  • 4
  • 14
Person1
  • 45
  • 1
  • 7
  • See https://stackoverflow.com/q/14426366/32880, https://stackoverflow.com/q/42433162/32880, and https://stackoverflow.com/q/37385007/32880 for details on limiting the values within Go. If you want to validate your YAML, you can create a custom `yaml.Unmarshaler`. – JimB Oct 12 '21 at 12:50

0 Answers0