In Go, there are several idiomatic approaches depending on your specific needs:
Using a map for O(1) lookup
The most common and efficient approach is to use a map with the valid values as keys:
func isValidStatus(status string) bool {
validStatuses := map[string]bool{
"active": true,
"inactive": true,
"pending": true,
"deleted": true,
}
return validStatuses[status]
}
You can also use an empty struct to save memory since you only care about key existence:
func isValidStatus(status string) bool {
validStatuses := map[string]struct{}{
"active": {},
"inactive": {},
"pending": {},
"deleted": {},
}
_, exists := validStatuses[status]
return exists
}
Using a switch statement
For a small number of values, a switch statement is clean and readable:
func isValidStatus(status string) bool {
switch status {
case "active", "inactive", "pending", "deleted":
return true
default:
return false
}
}
Using a slice with linear search
For very small sets or when you need to preserve order, you might use a slice:
func isValidStatus(status string) bool {
validStatuses := []string{"active", "inactive", "pending", "deleted"}
for _, valid := range validStatuses {
if status == valid {
return true
}
}
return false
}
Package-level constants
For values that don't change, consider defining them as package-level variables:
var validStatuses = map[string]struct{}{
"active": {},
"inactive": {},
"pending": {},
"deleted": {},
}
func isValidStatus(status string) bool {
_, exists := validStatuses[status]
return exists
}
The map approach is generally preferred for larger sets due to its O(1) lookup time, while the switch statement is often chosen for smaller sets due to its clarity and the compiler's optimization.