In Go, using the github.com/go-playground/validator package, you can validate fields to ensure they match one of a set of allowed values using the oneof tag. However, Go structs do not support default values natively, and the validator package does not handle setting default values.
That said, you can combine:
- Struct field tags with
oneof for validation
- Manual logic or another library to set default values
✅ Example: oneof for Enum Validation
Let’s say you have a Gender field that should be one of "male", "female", or "other".
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type User struct {
Name string `validate:"required"`
Gender string `validate:"oneof=Male Female Other"`
}
func main() {
validate := validator.New()
user := User{
Name: "Alice",
Gender: "Female", // valid
}
err := validate.Struct(user)
if err != nil {
fmt.Println("Validation failed:", err)
} else {
fmt.Println("Validation passed")
}
}
If Gender is empty or not one of the allowed values, validation will fail.
🚫 Default Value is Not Supported by Validator
The validator does not support setting a default value if the field is empty. So this won’t work:
Gender string `validate:"oneof=Male Female Other" default:"Other"`
Go does not support default values in struct tags, and validator doesn't add this behavior.
✅ Workaround: Set Default Manually
You can implement a method to set defaults before validation:
func (u *User) SetDefaults() {
if u.Gender == "" {
u.Gender = "Other"
}
}
Then call this before validation:
user := User{
Name: "Alice",
// Gender is omitted
}
user.SetDefaults()
err := validate.Struct(user)
Now Gender will default to "Other" and pass validation.
✅ Alternative: Use a Custom Validator or Struct Hook
You can also implement a custom validator or use struct-level validation to simulate default behavior, but setting defaults manually is clearer and more idiomatic.
✅ Bonus: Using oneof with Enums (IOTA)
If you're using typed constants (like iota enums), you'll need to ensure the string representation is used in the oneof tag:
type Role int
const (
Admin Role = iota
Editor
Viewer
)
// Then map to strings manually or via Stringer interface
For validation, it's often easier to use strings unless you're working with numeric enums in APIs.
Summary
| Feature | Supported? | Notes |
|---|
oneof enum validation | ✅ Yes | Use validate:"oneof=val1 val2" |
| Default value via tag | ❌ No | Go and validator don't support this |
| Set default manually | ✅ Yes | Preferred approach |
| IOTA enums | ✅ Yes (with care) | You'll need to convert to strings for validation |
Let me know if you want an example using json or mapstructure tags with defaults (e.g., for config structs).