Best way to parse a string to an enum

Viewed 4897

I have an enum as follows

type Capability int

const (
    Read   Capability = iota // Read   = 0
    Create                   // Create = 1
    Update                   // Update = 2
    Delete                   // Delete = 3
    List                     // List   = 4
)

I want to be able to get the string representation from the enum AS WELL AS parse a string to get the enum.

I get the string from the enum as follows.


capabilityStrs := []string{"read", "create", "update", "delete", "list"}
func (c Capability) String() string {
    return capabilityStrs[c]
}

How do I parse a string into an enum such that a call to ParseSTring("read") gives me Read`. What is the Best way to go about this?

2 Answers

Answer based on the comment by @super

var (
    capabilitiesMap = map[string]Capability{
        "read":   Read,
        "create": Create,
        "update": Update,
        "delete": Delete,
        "list":   List,
    }
)
func ParseString(str string) (Capability, bool) {
    c, ok := capabilitiesMap[strings.ToLower(str)]
    return c, ok
}

Whereas what defines 'best way' is dependable like @inian says, following is one approach

type Capability string

const (
    Read   Capability = "READ"
    Create Capability = "CREATE"
    Update Capability = "UPDATE"
    Delete Capability = "DELETE"
    List   Capability = "LIST"
)

func (c Capability)String()string{
    return string(c)
}

func ParseCapability(s string)(c Capability,err error){
    capabilities := map[Capability]struct{}{
        Read: {},
        Create: {},
        Update: {},
        Delete: {},
        List: {},
    }

    cap := Capability(s)
    _,ok := capabilities[cap]
    if !ok{
        return c,fmt.Errorf(`cannot parse:[%s] as capability`,s)
    }
    return cap,nil
}
Related