1
votes

I have created a strict like the following in my app:

type Datatype int8

const (
    user Datatype = iota
    address
    test
)

var datatypes = [...]string{"User", "Address", "Test"}

func (datatype Datatype) String() string {
    return datatypes[datatype]
}

I would like to be able to validate a value passed via a command-line flag against this enum.

I thought I had seen something like dtype == Datatype being used, but I am apparently sorely mistaken.

If this is not possible I can go the route of putting these values in an array. However, I feel the enum approach is more elegant.

1
Can you clarify "validate a value passed via a command-line flag against this enum"? Are you trying to see if a flag was passed on the command line? Validate user input? Check for non-default values in a struct?maerics
In addition to the above .. can you please show us this "struct" you're referring to? How does a struct come into play here? ... Are you sure you're not just looking for a map?Simon Whitehead
I was trying to do exactly what @IanNaN answered below. Thank you maerics and Simon I apologize for the confusion.RockyMountainHigh

1 Answers

4
votes

From your code sample it looks like you are trying to see if a map (rather than a struct) contains a particular key.

If so, the answer is here

A two-value assignment tests for the existence of a key:

i, ok := m["route"] 

In this statement, the first value (i) is assigned the value stored under the key "route". If that key doesn't exist, i is the value type's zero value (0). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

To test for a key without retrieving the value, use an underscore in place of the first value:

_, ok := m["route"]