Skip to content

Expand functionality for "Unknown" values #299

@MitchellBot

Description

@MitchellBot

Great project. Thank you for all your hard work!

I only have one request about handling "Unknown" values.

When creating enums, it's best practice to have a value that represents "Unknown" input. This helps with JSON marshaling and allows creating the object with a default value before setting it (helpful for pflags). For this situation though, the IsValid should return false for whichever value is Unknown. But when using an Unknown value with go-enum, it's treated as IsValid=true and also listed in the error message as a valid option.

Additionally, the integer for the unknown value should be assignable. For instance, I'm working with a backend enum that does not have an Unknown representation but uses index 0 for a valid type. However, even though the backend doesn't use Unknown types, I still wish to use it for the above mentioned reasons. Thus, I have to use -1, like so:

Example:

/* ENUM(
Unknown = -1
OneThing = 0
Something = 18
AnotherThing = 25
) */
type MyType int

This works to create an Unknown representation with value -1, but the Parse function automatically defaults to MyType(0) - whether it exists or not.

To summarize, the desired behavior is:

  • if someone tries to parse "YetAnotherThing", it should map to Unknown (-1), not MyType(0) which is OneThing
  • when the error prints, it should never say not a valid MyType, try [Unknown, ...] - it should only list the valid types
  • If we do parse an invalid value - and it gets mapped to Unknown - then IsValid() should not return true

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions