I am trying to write a generic function that takes a struct and confirms that the given fields have non-zero values.
This is my function:
func CheckRequiredFields(kind string, i interface{}, fields ...string) error {
for _, field := range fields {
value := reflect.ValueOf(i).FieldByName(field)
if value.Interface() == reflect.Zero(value.Type()).Interface() {
return fmt.Errorf("missing required %s field %s", kind, field)
}
}
return nil
}
and it works well if a struct is passed in as i, but fails if i is a pointer to a struct.
How can I reflect on the value of an interface if the value passed in is a pointer?
Aucun commentaire:
Enregistrer un commentaire