0

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?

1 Answer 1

1

You can use reflect.Indirect, which returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

If you want to check if the value was a pointer or not, check it's Kind, and use Elem() to dereference the pointer.

v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
    v = v.Elem()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I thought it would be something like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.